Pavan Kumar T S
Pavan Kumar T S

Reputation: 1559

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

Upvotes: 5

Views: 4111

Answers (1)

Alasdair
Alasdair

Reputation: 309049

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
        ...

Upvotes: 7

Related Questions