Using special characters in a Django template tags

I am trying to make a field with Django Tweaks and I am trying to add some HTMX attributes. I want to use the following syntax:

{% render_field field <other attributes> hx-vals='{"country": this.value}' %}

However, if I use this syntax, I get an rendering error. This is because it tries to interpret the brackets.

I have searched a lot on the internet, and each answer for escaping characters in Django Templates, suggests using the verbatim tag or something similar. The problem is that that only allows you to render special characters, not use them in a variable.

Is there a solution that allows me to escape special characters in Django template variables?

Right now I am sending the string in the context, but that is not ideal.

Thanks in advance!

I have solved the problem now by putting the special characters in seperate variables. I also had an issue with putting special characters in a URL, which I solved by putting in non-special characters and replacing them.

{% url 'subdivisions' 'replace' as full_url %}
{% with full_url|cut:"/replace"|add:"{country}" as full_url %}
  {% with "{'country': 'None'}" as hx_attrs %}
    {% render_field field hx-get=full_url hx-trigger="change" hx-target="#id_principal_subdivision" hx-swap="outerHTML" hx-attrs=hx_attrs %}
  {% endwith %}
{% endwith %}

A cleaner way to put in the URL would be appreciated.

Вернуться на верх