根据需要,Django Crispy表单设置模型字段

时间:2017-11-06 15:59:17

标签: python django django-forms django-crispy-forms

我有一个模型表单,我想在其中将必需属性设置为True以进行电子邮件验证

字段: - email

class RegisterMyBuisinessForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        self.helper = FormHelper()
        self.helper.form_method = 'post'
        self.helper.form_action = '/registermybuisness/'
        Field('email', type='email')
        self.helper.add_input(Submit('submit', 'Submit',css_class="btn c-theme-btn c-btn-square c-btn-bold c-btn-uppercase"))
        super(RegisterMyBuisinessForm, self).__init__(*args, **kwargs)
    class Meta:
        model = RegistermyBusiness
        fields = ['name','email', 'org_name', 'contact','business_description','store_address','message','store_landmark','business_type','city']        

我试过

self.fields['email'].required=True 

这导致类RegisterMyBuisinessForm没有字段错误

1 个答案:

答案 0 :(得分:3)

您可以在self.fields['email']方法中更改__init__。您需要先致电super()

class RegisterMyBuisinessForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        ...
        super(RegisterMyBuisinessForm, self).__init__(*args, **kwargs)
        self.fields['email'].required = True
        ...