Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django form field required conditionally

Tags:

I'd like to have a field which is required conditionally based on setting a boolean value to True or False.

What should I return to set required =True if is_company is set to True?

class SignupFormExtra(SignupForm):     is_company = fields.BooleanField(label=(u"Is company?"),                                       required=False)     NIP = forms.PLNIPField(label=(u'NIP'), required=False)      def clean(self):         if self.cleaned_data.get('is_company', True):             return ...?         else:             pass 
like image 266
Efrin Avatar asked Jun 10 '12 09:06

Efrin


People also ask

How do you make a field required in Django?

Let's try to use required via Django Web application we created, visit http://localhost:8000/ and try to input the value based on option or validation applied on the Field. Hit submit. Hence Field is accepting the form even without any data in the geeks_field. This makes required=False implemented successfully.

How do you remove this field is required Django?

If yes try to disable this behavior, set the novalidate attribute on the form tag As <form action="{% url 'new_page' %}", method="POST" novalidate> in your html file.

What is CharField in Django?

CharField is a commonly-defined field used as an attribute to reference a text-based database column when defining Model classes with the Django ORM. The Django project has wonderful documentation for CharField and all of the other column fields.


1 Answers

Check the Chapter on Cleaning and validating fields that depend on each other in the documentation.

The example given in the documentation can be easily adapted to your scenario:

def clean(self):     cleaned_data = super(SignupFormExtra, self).clean()     is_company = cleaned_data.get("is_company")     nip = cleaned_data.get("NIP")     if is_company and not nip:         raise forms.ValidationError("NIP is a required field.")     return cleaned_data 
like image 89
arie Avatar answered Oct 03 '22 00:10

arie