Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django modelform NOT required field

I have a form like this:

class My_Form(ModelForm):     class Meta:         model = My_Class         fields = ('first_name', 'last_name' , 'address') 

How can I set the address field as optional?

like image 993
Andres Avatar asked Apr 25 '13 03:04

Andres


People also ask

How do you make a field not required in Django?

The simplest way is by using the field option blank=True (docs.djangoproject.com/en/dev/ref/models/fields/#blank).

How do you make a form field not required?

Just add blank=True in your model field and it won't be required when you're using modelforms .

How do you make a field optional in Django?

If you want to allow blank values in a date field (e.g., DateField , TimeField , DateTimeField ) or numeric field (e.g., IntegerField , DecimalField , FloatField ), you'll need to use both null=True and blank=True . Show activity on this post. Use null=True and blank=True in your model.

How do you make a field not editable in Django?

The disabled boolean argument, when set to True , disables a form field using the disabled HTML attribute so that it won't be editable by users. Even if a user tampers with the field's value submitted to the server, it will be ignored in favor of the value from the form's initial data.


2 Answers

class My_Form(forms.ModelForm):     class Meta:         model = My_Class         fields = ('first_name', 'last_name' , 'address')      def __init__(self, *args, **kwargs):         super(My_Form, self).__init__(*args, **kwargs)         self.fields['address'].required = False 
like image 142
madzohan Avatar answered Sep 19 '22 14:09

madzohan


Guess your model is like this:

class My_Class(models.Model):      address = models.CharField() 

Your form for Django version < 1.8:

class My_Form(ModelForm):      address = forms.CharField(required=False)      class Meta:         model = My_Class         fields = ('first_name', 'last_name' , 'address') 

Your form for Django version > 1.8:

class My_Form(ModelForm):      address = forms.CharField(blank=True)      class Meta:         model = My_Class         fields = ('first_name', 'last_name' , 'address') 
like image 20
Akshar Raaj Avatar answered Sep 17 '22 14:09

Akshar Raaj