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?
The simplest way is by using the field option blank=True (docs.djangoproject.com/en/dev/ref/models/fields/#blank).
Just add blank=True in your model field and it won't be required when you're using modelforms .
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.
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.
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
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With