Django modelform NOT required field
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')
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
field = models.CharField(max_length=9, default='', blank=True)
Just add blank=True
in your model field and it won't be required when you're using modelforms
.
"If the model field has blank=True
, then required is set to False on the form field. Otherwise, required=True
."
source: https://docs.djangoproject.com/en/3.1/topics/forms/modelforms/#field-types