简体   繁体   中英

Django Crispy form set model field as required

I have a modelform in which I want to set required attribute to True for email validation

field:- 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']        

I tried

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

this resulted in class RegisterMyBuisinessForm doesnot have fields error

You can alter self.fields['email'] in the __init__ method. You need to call super() first.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM