Django modelform NOT required field

Solution 1:

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

Solution 2:

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')

Solution 3:

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

Solution 4:

You would have to add:

address = forms.CharField(required=False)

Solution 5:

Solution: use both blank=True, null=True.

my_field = models.PositiveIntegerField(blank=True, null=True)

Explanation:

If you use null=True

my_field = models.PositiveIntegerField(null=True)

then my_field is required, with * next to it in the form and you can't submit the empty value.

If you use blank=True

my_field = models.PositiveIntegerField(blank=True)

then my_field is not required, there won't be a * next to it in the form and you can't submit the value. But it will get null field not allowed.

Note: marking as not required and allowing null fields are two different things.

Pro Tip: Read the error more carefully than documentation.