djangodjango-widget-tweaks

How to remove required from Django-Widget-Tweaks form field


I am trying to remove the required attribute from a django-widget-tweaks form.

I tried:

{% render_field form.legal_entity|attr:'required:false' placeholder=form.legal_entity.label class+="form-control" %}

and

{% render_field form.legal_entity|remove_attr:"required" placeholder=form.legal_entity.label class+="form-control" %}

No matter what I do, the result is always:

<input type="text" name="legal_entity" maxlength="120" class="form-control" placeholder="Firmenname" required id="id_legal_entity">

Here is the according Form:

class MerchantForm(forms.ModelForm):

    class Meta:
        model = Merchant
        fields = ['name', 'legal_entity', 'legal_address','legal_zip', 'legal_city','address', 'zip', 'city', 'contact_person', 'phone', 'email']

 def clean_legal_entity(self):
        data = self.cleaned_data['legal_entity']
        return data

...


Solution

  • You can mark the field as non-required by setting required=False [Django-doc] in the corresponding field:

    class MerchantForm(forms.ModelForm):
        legal_entity = forms.CharField(required=False)
    
        class Meta:
            model = Merchant
            fields = ['name', 'legal_entity', 'legal_address','legal_zip', 'legal_city','address', 'zip', 'city', 'contact_person', 'phone', 'email']