2

In the django documentation there is information that by declaring a model field of type CharField as blank=True, the form will not require filling in the respective field. However, in my project that is not working. To make a field not mandatory in the form, the only alternative I found was to define it as required=False. I am using Django 3.0.2.

If the form does not have the field defined in the model with blank=True, then there is no error. But if the form has this field, it only works if i add required=False to the form field, otherwise it will be mandatory even though it was defined in the model with blank=True.

Same behavior in Django 2.2.

Same behavior in Django 1.11.17

Carlos Ribeiro
  • 130
  • 1
  • 8
  • I think you will get your answer after reading this [answer](https://stackoverflow.com/a/8609425/9246099). – dipesh Feb 13 '20 at 16:46
  • Using blank=True and default='' for the name field of a model class, in the python console, it is possible to instantiate an object (without providing a value for the name field) and save it in the database with the save() method, but if I try to do the same thing using a form field that does not have required=False, django requires filling in the name field. – Carlos Ribeiro Feb 13 '20 at 18:41

1 Answers1

2

The answer to my question is as follows:

Suppose you have defined the following class:

class Client (models.Model):
    name = models.CharField (max_length=100, blank=True)
    address = models.CharField (max_length=100, blank=False)

If the form class has been defined like this:

class ClientForm (ModelForm):
    class Meta:
        model = Client
        fields = ['name', 'address']
        widgets = {
            'name': forms.TextInput (attrs = {'class': 'form-control form-control-sm'}),
            'address': forms.TextInput (attrs = {'class': 'form-control form-control-sm'})
        }

Then, the 'name' field will not be mandatory (due to the blank=True in the model) and the 'address' field will be mandatory (due to the blank=False in the model).

However, if the ClientForm class has been defined like this:

class ClientForm (ModelForm):
    class Meta:
        model = Client
        fields = ['name', 'address']

    name = forms.CharField (
        widget = forms.TextInput (attrs = {'class': 'form-control form-control-sm'}),
    )
    address = forms.CharField (
        widget = forms.TextInput (attrs = {'class': 'form-control form-control-sm'}),
    )

Then, both fields ('name' and 'address') will be mandatory, "since fields defined declaratively are left as-is" (https://docs.djangoproject.com/en/3.0/topics/forms/modelforms/), i.e. the default for the 'required' attribute of the form field is True and this will require that the fields 'name' and 'address' are filled, even if, in the model, the field has been set to blank=True.

Carlos Ribeiro
  • 130
  • 1
  • 8