Skip to content

Instantly share code, notes, and snippets.

@ekinertac
Last active April 15, 2024 08:38
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ekinertac/5c5e795a6d521e4c8190 to your computer and use it in GitHub Desktop.
Save ekinertac/5c5e795a6d521e4c8190 to your computer and use it in GitHub Desktop.
Django null/blank field explanation
Fields null=True blank=True
CharField, TextField, SlugField, EmailField, CommaSeparatedIntegerField DON'T Django's convention is to store empty values as the empty string, and to always retrieve NULL or empty values as the empty string for consistency. OK Do this if you want the corresponding form widget to accept empty values. If you set this, empty values get stored as empty strings in the database.
BooleanField DON'T Use NullBooleanField instead. DON'T
IntegerField, FloatField, DecimalField OK If you wabt to be able to set the value to NULL in the database OK if you want the corresponding form widget to accept empty values. if so out will also want to set null=True
DateTimeField, DateField, TimeField OK if you want to be able to set the value to NULL in the database. OK If you want the corresponding form widget to accept empty values, or if you are using auto now or auto now add. If so, you will also want to set null=True.
ForeignKey, ManyToManyField, OneToOneField OK if you want to be able to set the value to NULL in the database.. OK if you want the corresponding form widget (e.g. the select box) to accept empty values.
IPAddressField, GenericIPAddressField OK if you want to be able to set the value to NULL in the database. NOT RECOMMENDED In PostgreSQL, the native inet type is used here and cannot be set to the empty string. (Other database backends use char or varchar for this, though.)

Note: IPAddressField in PostgreSQL. At the time of this writing, there is an open ticket (#5622) related to IPAddressFields: ‘Empty ipaddress raises an error (invalid input syntax for type inet: "") [sic].’ Until this ticket is resolved, we recommend using null=True and blank=False with IPAddressFields. See http://code.djangoproject.com/ticket/5622 for more details

Field Use
CharField blank=True
TextField blank=True
SlugField blank=True
EmailField blank=True
CommaSeparatedIntegerField blank=True
BooleanField use NullBooleanField
IntegerField blank=True, null=True
FloatField blank=True, null=True
DecimalField blank=True, null=True
DateTimeField blank=True, null=True
DateField blank=True, null=True
TimeField blank=True, null=True
ForeignKey blank=True, null=True
ManyToManyField blank=True, null=True
OneToOneField blank=True, null=True
IPAddressField null=True
GenericIPAddressField null=True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment