【问题标题】:Django Crispy form set model field as requiredDjango Crispy 表单根据需要设置模型字段
【发布时间】:2018-04-18 20:27:38
【问题描述】:

我有一个模型表单,我想在其中将 required 属性设置为 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 没有字段错误

【问题讨论】:

  • 请注意,您在表单类的名称和form_action 中拼错了Business

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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-02
    • 2019-04-15
    • 2020-01-21
    • 2013-07-21
    • 2015-01-17
    • 2020-11-30
    • 1970-01-01
    • 2019-06-11
    相关资源
    最近更新 更多