如何从 Django-Widget-Tweaks 表单字段中删除 required

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

我正在尝试从 django-widget-tweaks 表单中删除必需的属性。

我试过了:

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

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

无论我做什么,结果总是:

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

这是相应的表格:

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

...

在您 HTML 页面的 JS 代码中:

 window.onload=myfunction();
 function myfunction()
{
    $("input").removeAttr("required");
    $("select").removeAttr("required");
    $("textarea").removeAttr("required");
}

您可以通过在相应字段中设置 required=False [Django-doc] 将字段标记为非必填:

class MerchantForm(forms.ModelForm):
    legal_entity = forms.CharField(<b>required=False</b>)

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