Django - Null and Blank Difference

Asked

Viewed 1,897 times

3

I’m having a hard time understanding the real difference between null and blank on Django,

For example:

In this code, to my understanding the name field will be NOTNULL in the database, but what about this Blank? It is not redundant with null???

class Empregado(models.Model):
    nome = models.CharField(max_length=70, blank=False, null=False)

2 answers

5

As to the null is correct. When using null=False the column will be on the bench as NOT NULL; the contrary is also valid.

As to the blank, it will define the behavior of the application when the value is empty (and empty is different from null).

inserir a descrição da imagem aqui

When using blank=False you are saying that the value of this field cannot be empty, that is, it will be mandatory when filling in the form. It will have much more impact on Python itself during validations than on the database itself.

4


If you define null=True (unlike NOT NULL) in a field of your template (a BD column), when entering empty values for types like DateTimeField and ForeignKey will be stored as NULL in your BD, this is very useful for Fks, when you want the related item to be left blank.

Defining blank=True you do not require the field to be filled in the forms, and may remain blank if you define blank=False this field shall be mandatory, that is, it shall not remain blank.

The combination of the two, at first glance, may not seem to make sense, but if you look at it from the perspective of front-end harmony with the back-end, you will see that if you allow a field to be blank (ie omitted) in a form, you will also need the database to allow NULL values for this field, with the exception of CharFields and TextFields which are stored as an empty string ('') instead of NULL, in Django.

In the documentation has the following note in explaining blank:
Note that blank is different from null. null is specifically related to the database, while the blank is related to validation. If a field has blank=True, the validation of a form will allow the entry of an empty value. If the field has blank=False, then the field will be mandatory.

  • Thank you, you helped me a lot!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.