Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - template - check if a field has attribute

forms.py

class someForm(forms.ModelForm):
    class Meta:
        model = someModel
        field = '__all__'
        widgets = {'length': forms.TextInput(attrs={'class': 'has-checkbox'})}

I gave a form field an attribute like the above. The goal is to add an HTML code row that has checkbox. Something like this:

{% if field hasAttr('has-checkbox') %}
    <input type="checkbox">
    {{ field }}
{% end if %}

The problem is that I do not know Django Template version of code that does what hasAttr() does. This is a random function that I just made up to ask question here. How can I do this?

like image 552
Eric Kim Avatar asked Nov 01 '25 16:11

Eric Kim


1 Answers

You can access the widget with field.field.widget so something like this should work:

{% if 'has-checkbox' in field.field.widget.attrs.class %}
    <input type="checkbox">
    {{ field }}
{% endif %}
like image 156
Cyrlop Avatar answered Nov 04 '25 10:11

Cyrlop



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!