Search code examples
djangodjango-templatesdjango-widget-tweaks

How do I escape single quotes in a django-widget-tweaks's render_field tag?


I'm trying to use django-widget-tweaks to render the following form field:

{% render_field profile_form.bio class+="form-control" id="bio" rows="3" oninput="showBtn('updateProfile')" %}

Into this:

<textarea class="form-control" id="bio" rows="3" oninput="showBtn('updateProfile')"></textarea>

However, I'm getting a parsing error as Django is changing the single quotes in the widget into double quotes.

The showBtn js function is as follows:

// Shows a button given an id
showBtn: function (selector) {
  let btn = document.getElementById(selector);
  btn.classList.remove("btn-hidden");
}

The reason why I use django-widget-tweaks is to keep all html classes and attributes isolated in the templates.

What I already tried:

  • representing the single quote as text entity &#39;. It renders the template (no parsing error), but does't actually replace the ascii into quotes so the js is never triggered
  • escaping with slashes
  • using the safe templatetag
  • using the autoescape templatetag

For reference, here is the form model:

# forms.py
class ProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ["bio"]

And the original model:

# models.py
class Profile(models.Model):
    """ Non-auth related user information about an user"""
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(max_length=500, blank=True)

Solution

  • Ok... so this is how I eventually solved it.

    Instead of using a syntax similar to plain HTML attributes (which is why I liked django-widget-tweaks in the first place), the packages' templatetags works. But this like a workaround for some bug django-widget-tweaks has.

    {% render_field profile_form.bio|add_class:"form-control"|attr:"id:bio"|attr:"rows:3"|attr:"oninput:showBtn('updateProfile')" %}
    

    This way the oninput attribute is parsed correctly.