Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 500
Pavan Kumar T S Avatar asked Nov 06 '17 15:11

Pavan Kumar T S


People also ask

How do you make a model field required in Django?

In order to make the summary field required, we need to create a custom form for the Post model. I am making them on the same file you can do this on a separate forms.py file as well. As intended we create the custom model form and in the __init__ method we made the summary field required.

How does Django implement crispy forms?

Installation of django-crispy-forms is quite standard. You will need to use a package manager "pip" or "easy_install", then add an installed application 'crispy_forms' to the INSTALLED_APPS list. If you plan on using Bootstrap (or any other CSS framework), then you will also have to import it to the project.

What is FormHelper in Django?

FormHelper(form=None)[source] This class controls the form rendering behavior of the form passed to the {% crispy %} tag. For doing so you will need to set its attributes and pass the corresponding helper object to the tag: {% crispy form form.


1 Answers

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
        ...
like image 186
Alasdair Avatar answered Sep 30 '22 18:09

Alasdair