1595👍
null=True
sets NULL
(versus NOT NULL
) on the column in your DB. Blank values for Django field types such as DateTimeField
or ForeignKey
will be stored as NULL
in the DB.
blank
determines whether the field will be required in forms. This includes the admin and your custom forms. If blank=True
then the field will not be required, whereas if it’s False
the field cannot be blank.
The combo of the two is so frequent because typically if you’re going to allow a field to be blank in your form, you’re going to also need your database to allow NULL
values for that field. The exception is CharField
s and TextField
s, which in Django are never saved as NULL
. Blank values are stored in the DB as an empty string (''
).
A few examples:
models.DateTimeField(blank=True) # raises IntegrityError if blank
models.DateTimeField(null=True) # NULL allowed, but must be filled out in a form
Obviously, Those two options don’t make logical sense to use (though there might be a use case for null=True, blank=False
if you want a field to always be required in forms, optional when dealing with an object through something like the shell.)
models.CharField(blank=True) # No problem, blank is stored as ''
models.CharField(null=True) # NULL allowed, but will never be set as NULL
CHAR
and TEXT
types are never saved as NULL
by Django, so null=True
is unnecessary. However, you can manually set one of these fields to None
to force set it as NULL
. If you have a scenario where that might be necessary, you should still include null=True
.
169👍
This is how the ORM maps blank
& null
fields for Django 1.8
class Test(models.Model):
charNull = models.CharField(max_length=10, null=True)
charBlank = models.CharField(max_length=10, blank=True)
charNullBlank = models.CharField(max_length=10, null=True, blank=True)
intNull = models.IntegerField(null=True)
intBlank = models.IntegerField(blank=True)
intNullBlank = models.IntegerField(null=True, blank=True)
dateNull = models.DateTimeField(null=True)
dateBlank = models.DateTimeField(blank=True)
dateNullBlank = models.DateTimeField(null=True, blank=True)
The database fields created for PostgreSQL 9.4 are :
CREATE TABLE Test (
id serial NOT NULL,
"charNull" character varying(10),
"charBlank" character varying(10) NOT NULL,
"charNullBlank" character varying(10),
"intNull" integer,
"intBlank" integer NOT NULL,
"intNullBlank" integer,
"dateNull" timestamp with time zone,
"dateBlank" timestamp with time zone NOT NULL,
"dateNullBlank" timestamp with time zone,
CONSTRAINT Test_pkey PRIMARY KEY (id)
)
The database fields created for MySQL 5.6 are :
CREATE TABLE Test (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`charNull` VARCHAR(10) NULL DEFAULT NULL,
`charBlank` VARCHAR(10) NOT NULL,
`charNullBlank` VARCHAR(10) NULL DEFAULT NULL,
`intNull` INT(11) NULL DEFAULT NULL,
`intBlank` INT(11) NOT NULL,
`intNullBlank` INT(11) NULL DEFAULT NULL,
`dateNull` DATETIME NULL DEFAULT NULL,
`dateBlank` DATETIME NOT NULL,
`dateNullBlank` DATETIME NULL DEFAULT NULL
)
- [Django]-Using django-rest-interface
- [Django]-How to save pillow image object to Django ImageField?
- [Django]-Create a field whose value is a calculation of other fields' values
151👍
It’s crucial to understand that the options in a Django model field definition serve (at least) two purposes: defining the database tables, and defining the default format and validation of model forms. (I say "default" because the values can always be overridden by providing a custom form.) Some options affect the database, some options affect forms, and some affect both.
When it comes to null
and blank
, other answers have already made clear that the former affects the database table definition and the latter affects model validation. I think the distinction can be made even clearer by looking at use cases for all four possible configurations:
-
null=False
,blank=False
: This is the default configuration and means that the value is required in all circumstances. -
null=True
,blank=True
: This means that the field is optional in all circumstances. As noted below, though, this is not the recommended way to make string-based fields optional. -
null=False
,blank=True
: This means that the form doesn’t require a value but the database does. There are a number of use cases for this:-
The most common use is for optional string-based fields. As noted in the documentation, the Django idiom is to use the empty string to indicate a missing value. If
NULL
was also allowed you would end up with two different ways to indicate a missing value. (If the field is alsounique
, though, you’ll have to usenull=True
to prevent multiple empty strings from failing the uniqueness check.) -
Another common situation is that you want to calculate one field automatically based on the value of another (in your
save()
method, say). You don’t want the user to provide the value in a form (henceblank=True
), but you do want the database to enforce that a value is always provided (null=False
). -
Another use is when you want to indicate that a
ManyToManyField
is optional. Because this field is implemented as a separate table rather than a database column,null
is meaningless. The value ofblank
will still affect forms, though, controlling whether or not validation will succeed when there are no relations.
-
-
null=True
,blank=False
: This means that the form requires a value but the database doesn’t. This may be the most infrequently used configuration, but there are some use cases for it:-
It’s perfectly reasonable to require your users to always include a value even if it’s not actually required by your business logic. After all, forms are only one way of adding and editing data. You may have code that is generating data that doesn’t need the same stringent validation you want to require of a human editor.
-
Another use case that I’ve seen is when you have a
ForeignKey
for which you don’t wish to allow cascade deletion. That is, in normal use the relation should always be there (blank=False
), but if the thing it points to happens to be deleted, you don’t want this object to be deleted too. In that case you can usenull=True
andon_delete=models.SET_NULL
to implement a simple kind of soft deletion.
-
- [Django]-Django: show the count of related objects in admin list_display
- [Django]-Django 1.5b1: executing django-admin.py causes "No module named settings" error
- [Django]-Using django-admin on windows powershell
70👍
You may have your answer however till this day it’s difficult to judge whether to put null=True
or blank=True
or both to a field. I personally think it’s pretty useless and confusing to provide so many options to developers. Let the handle the nulls or blanks however they want.
I follow this table, from Two Scoops of Django:
- [Django]-Missing Table When Running Django Unittest with Sqlite3
- [Django]-Laravel's dd() equivalent in django
- [Django]-Best practices for getting the most testing coverage with Django/Python?
61👍
As said in Django Model Field reference: Link
Field options
The following arguments are available to all field types. All are optional.
null
Field.null
If
True
, Django will store empty values asNULL
in the database. Default isFalse
.Avoid using
null
on string-based fields such asCharField
and
TextField
because empty string values will always be stored as empty
strings, not asNULL
. If a string-based field hasnull=True
, that
means it has two possible values for “no data”:NULL
, and the empty
string. In most cases, it’s redundant to have two possible values for
“no data”; the Django convention is to use the empty string, not
NULL
.For both string-based and non-string-based fields, you will also need
to setblank=True
if you wish to permit empty values in forms, as
thenull
parameter only affects database storage (seeblank
).Note
When using the Oracle database backend, the value NULL will be stored to denote the empty string regardless of this attribute
blank
Field.blank
If
True
, the field is allowed to be blank. Default isFalse
.Note that this is different than
null
.null
is purely
database-related, whereasblank
is validation-related. If a field
hasblank=True
, form validation will allow entry of an empty value.
If a field hasblank=False
, the field will be required.
- [Django]-On Heroku, is there danger in a Django syncdb / South migrate after the instance has already restarted with changed model code?
- [Django]-Django admin file upload with current model id
- [Django]-Django {% if forloop.first %} question
34👍
Simply null=True
defines database should accept NULL
values, on other hand blank=True
defines on form validation this field should accept blank values or not(If blank=True
it accept form without a value in that field and blank=False
[default value] on form validation it will show This field is required error.
null=True/False
related to database
blank=True/False
related to form validation
- [Django]-What is the difference between cached_property in Django vs. Python's functools?
- [Django]-Testing nginx without domain name
- [Django]-Choose test database?
23👍
Here is an example of the field with blank= True
and null=True
description = models.TextField(blank=True, null= True)
In this case:
blank = True
: tells our form that it is ok to leave the description field blank
and
null = True
: tells our database that it is ok to record a null value in our db field and not give an error.
- [Django]-Django apps aren't loaded yet when using asgi
- [Django]-How to run a celery worker with Django app scalable by AWS Elastic Beanstalk?
- [Django]-Paginating the results of a Django forms POST request
12👍
If you set null=True
, it will allow the value of your database column to be set as NULL
. If you only set blank=True
, django will set the default new value for the column equal to ""
.
There’s one point where null=True
would be necessary even on a CharField
or TextField
and that is when the database has the unique
flag set for the column. In this case you’ll need to use this:
a_unique_string = models.CharField(blank=True, null=True, unique=True)
Preferrably skip the null=True
for non-unique CharField
or TextField
. Otherwise some fields will be set as NULL
while others as ""
, and you’ll have to check the field value for NULL
everytime.
- [Django]-Troubleshooting Site Slowness on a Nginx + Gunicorn + Django Stack
- [Django]-How to implement followers/following in Django
- [Django]-Cross domain at axios
9👍
The default values of null
and blank are False
.
Null
: It is database-related. Defines if a given database column will accept null values or not.
Blank
: It is validation-related. It will be used during forms validation, when calling form.is_valid()
.
That being said, it is perfectly fine to have a field with null=True
and blank=False
. Meaning on the database level the field can be NULL
, but in the application level it is a required field.
Now, where most developers get it wrong: Defining null=True
for string-based fields such as CharField
and TextField
. Avoid doing that. Otherwise, you will end up having two possible values for “no data”, that is: None
and an empty string. Having two possible values for “no data” is redundant. The Django convention is to use the empty string, not NULL
.
- [Django]-Heroku, postgreSQL, django, comments, tastypie: No operator matches the given name and argument type(s). You might need to add explicit type casts
- [Django]-Login Page by using django forms
- [Django]-Add additional options to Django form select widget
8👍
null = True
Means there is no constraint of database for the field to be filled, so you can have an object with null value for the filled that has this option.
blank = True
Means there is no constraint of validation in django forms. so when you fill a modelForm
for this model you can leave field with this option unfilled.
- [Django]-Django: Grab a set of objects from ID list (and sort by timestamp)
- [Django]-How do I use django rest framework to send a file in response?
- [Django]-Get the list of checkbox post in django views
7👍
Here, is the main difference of null=True
and blank=True
:
The default value of both null
and blank
is False. Both of these values work at field level i.e., whether we want to keep a field null
or blank
.
null=True
will set the field’s value to NULL
i.e., no data. It is basically for the databases column value.
date = models.DateTimeField(null=True)
blank=True
determines whether the field will be required in forms. This includes the admin and your own custom forms.
title = models.CharField(blank=True) // title can be kept blank.
In the database ("")
will be stored.
null=True
blank=True
This means that the field is optional in all circumstances.
epic = models.ForeignKey(null=True, blank=True)
// The exception is CharFields() and TextFields(), which in Django are never saved as NULL. Blank values a
- [Django]-How to deal with "SubfieldBase has been deprecated. Use Field.from_db_value instead."
- [Django]-Django: For Loop to Iterate Form Fields
- [Django]-Django celery task: Newly created model DoesNotExist
6👍
null = True || blank = True || null = True && blank = True
class TestModel(models.Model):
field1 = models.CharField(max_length=100, null=True)
field2 = models.CharField(max_length=100, blank=True) # it's not a correct way
field3 = models.CharField(max_length=100, null=True, blank=True)
THE DB FIELDS FOR: MySQL
CREATE TABLE TestModel (
`id` INT(10) NOT NULL AUTO_INCREMENT,
`field1` VARCHAR(100) NULL DEFAULT NULL,
`field2` VARCHAR(100) NOT NULL,
`field3` VARCHAR(100) NULL DEFAULT NULL,
)
case-01: null = True
db: db field is accepts null value
form: form field is `required`
NB: DB IS ACCEPTS NULL VALUE, BUT FORM FIELD IS REQUIRED. SO FORM IS
SUBMITTED WHEN THIS FIELD HAVE SOME VALUE. it's good.
case-02: blank = True
db: db field is not accepts null value
form: form field is `optional`
NB: FORM IS VALID WITHOUT ANY VALUE, BUT DB IS NOT ACCEPTS NULL VALUE.
SO THE FORM IS SUBMITTED WITHOUT ANY VALUE THEN BOOM. it's worst.
case-03: null = True && blank = True
db: db field is accepts null value
form: form field is `optional`
NB: HERE FORM FIELD IS OPTIONAL & FORM IS VALID WITHOUT ANY VALUE
& DB ALSO ACCEPTS NULL VALUE. SO, IT'S BEST TO USE `null=True && blank=True`
🙂
- [Django]-Django Admin app or roll my own?
- [Django]-Explicitly set MySQL table storage engine using South and Django
- [Django]-What is more efficient .objects.filter().exists() or get() wrapped on a try
5👍
When we save anything in Django admin two steps validation happens, on Django level and on Database level. We can’t save text in a number field.
Database has data type NULL
, it’s nothing. When Django creates columns in the database it specifies that they can’t be empty. And if you will try to save NULL
you will get the database error.
Also on Django-Admin level, all fields are required by default, you can’t save blank field, Django will throw you an error.
So, if you want to save blank field you need to allow it on Django and Database level.
blank=True
– will allow empty field in admin panel
null=True
– will allow saving NULL
to the database column.
- [Django]-What is the purpose of adding to INSTALLED_APPS in Django?
- [Django]-Are sessions needed for python-social-auth
- [Django]-Serializer call is showing an TypeError: Object of type 'ListSerializer' is not JSON serializable?
4👍
null is for database and blank is for fields validation that you want to show on user interface like textfield to get the last name of person.
If lastname=models.charfield (blank=true) it didnot ask user to enter last name as this is the optional field now.
If lastname=models.charfield (null=true) then it means that if this field doesnot get any value from user then it will store in database as an empty string ” “.
- [Django]-Annotate a queryset with the average date difference? (django)
- [Django]-Paginate relationship in Django REST Framework?
- [Django]-Django form fails validation on a unique field
4👍
Here is its answer in simple words:-
By null = True
we are telling the database that this field of the model could be NULL, by blank = True
we are telling Django that this field of the model could be NULL
- [Django]-Django: Record with max element
- [Django]-What is the difference between cached_property in Django vs. Python's functools?
- [Django]-Django.contrib.gis.db.backends.postgis vs django.db.backends.postgresql_psycopg2
- [Django]-Python 3 list(dictionary.keys()) raises error. What am I doing wrong?
- [Django]-What is more efficient .objects.filter().exists() or get() wrapped on a try
- [Django]-Cross domain at axios
3👍
Null is purely database-related, whereas blank is validation-related. If a field has blank=True , validation on Django’s admin site will allow entry of an empty value. If a field has blank=False , the field will be required
- [Django]-Do django db_index migrations run concurrently?
- [Django]-Django Cache cache.set Not storing data
- [Django]-Django, Models & Forms: replace "This field is required" message
3👍
Blank=False # this field is required.
Null=False # this field should not be null
Blank=True # this field is optional.
Null=True # Django uses empty string (''), not NULL.
Note:
Avoid using null=True
on string-based fields such as CharField
and TextField
and FileField
/ImageField
.
Ref: Django null , Django blank
- [Django]-How to use Django ImageField, and why use it at all?
- [Django]-How to delete project in django
- [Django]-Django 1.5b1: executing django-admin.py causes "No module named settings" error
2👍
In Very simple words,
Blank is different than null.
null is purely database-related, whereas blank is validation-related(required in form).
If null=True
, Django will store empty values as NULL in the database
. If a field has blank=True
, form validation will allow entry of an empty value
. If a field has blank=False, the field will be required.
- [Django]-How to access request body when using Django Rest Framework and avoid getting RawPostDataException
- [Django]-Form with CheckboxSelectMultiple doesn't validate
- [Django]-Django content-type : how do I get an object?
2👍
null=True
and blank=True
are fields attributes in django.db.models. null is database related while blank is validation related.
null
The default is null=False
. If null=False, Django will not allow NULL values in the database column.
If null=True
, Django will store empty values as NULL in the database column. For CharField and TextField, django will use empty string ” instead of NULL. Avoid using null attribute for CharField and TextField. One exception is when CharField has unique=True
and blank=True
, then null=True
is required.
blank
The default is blank=False
. If blank=False, the field will be required.
If blank=True
, the field is optional and can be left blank. blank=True with null=False will require implementing clean() on model to programmatically set any missing values.
- [Django]-How to use subquery in django?
- [Django]-How do you Serialize the User model in Django Rest Framework
- [Django]-Add inline model to django admin site
1👍
null – default is False
if True, Django will store empty as null in the database.
blank – default is False
if true that field is allowed to be blank
more, goto
https://docs.djangoproject.com/en/3.0/topics/db/models/
- [Django]-How do I reuse HTML snippets in a django view
- [Django]-Equivalent of PHP "echo something; exit();" with Python/Django?
- [Django]-Django: How to get related objects of a queryset?
1👍
This table below demonstrates the main differences:
+--------------------------------------------------------------------+
| Purpose | null=True | blank = True |
|--------------------------|------------------|----------------------|
| Field can be empty in DB | Do this | Unaffected |
|--------------------------|------------------|----------------------|
| ModelForm(required field)| Unaffected | field not required |
|--------------------------|------------------|----------------------|
| Form Validation | Unaffected | field not required |
|--------------------------|------------------|----------------------|
| on_delete=SET_NULL | Need this | Unaffected |
+--------------------------------------------------------------------+
- [Django]-How to add a cancel button to DeleteView in django
- [Django]-Django: Open uploaded file while still in memory; In the Form Clean method?
- [Django]-Allowing only super user login
1👍
The meaning of null=True and blank=True in the model also depends on how these fields were defined in the form class.
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.
- [Django]-Django-taggit – how do I display the tags related to each record
- [Django]-How to add a cancel button to DeleteView in django
- [Django]-How to test Django's UpdateView?
1👍
blank=True
can be set to any model field to control whether that field can be left empty when entering a value in a form. Here, we are talking about entering data.
null=True
, if we set blank=True
for a field, that model field does not receive any value, then the database or Django has to do something with that field when data is written into the database. For any kind of text content an empty string is stored in the database, so there is a value stored in the database. For other kinds of fields like date fields or numbers, we use the special data type "null". "null" can be used if a field potentially has no value, but by default, Django does not allow "null" values. That is why you need to explicitly set null=True
.
Let’s say you set blank=True
, for any non-text fields, but you did not specify "null=True", Django will not know what to store and it would throw an error.
- [Django]-Django select_for_update cannot be used outside of a transaction
- [Django]-How can I get tox and poetry to work together to support testing multiple versions of a Python dependency?
- [Django]-Inline in ModelForm
1👍
According to the documentation, null is truly database related. If null=true, DB will store null inputs as null. Otherwise, empty strings are stored as empty strings.
Whereas, if blank=true, form will validate it as ok, else the field will be considered ‘required’ by form.
Both are by default false.
- [Django]-AccessDenied when calling the CreateMultipartUpload operation in Django using django-storages and boto3
- [Django]-What is the difference render() and redirect() in Django?
- [Django]-Django: How can I create a multiple select form?
0👍
When you set null=true
it will set null
in your database if the field is not filled. If
you set blank=true
it will not set any value to the field.
- [Django]-Is this the right way to do dependency injection in Django?
- [Django]-Pagination in Django-Rest-Framework using API-View
- [Django]-How to pass multiple values for a single URL parameter?
0👍
When you say null=False, it means a data must be pass to the database to be saved. When you say blank=False it means a data must be inputed from your frontend and vice versa
- [Django]-How to test auto_now_add in django
- [Django]-Use Python standard logging in Celery
- [Django]-Error when using django.template
0👍
Each option in the Django model serves two purposes
- Defining field constraints at the Database level (e.g SQL, Postgresql, or any other)
- Defining field constraints at the Form level ( At the framework level that is above the database layer)
Now Let’s get back to null
and blank
blank
is Django forms related. It is used for validation of Django forms, in admin or Django. Specifically when we callform.is_valid()
null
is database-related. It tells the underlying database whether the column would allownull
value to be saved or not.
For example, let’s see the below example-
class Company(models.Model):
name = models.CharField(max_length=100)
website = models.UrlField()
founded_on = models.DateField(blank=True, null=False)
random_date = models.DateFeild(blank=False, null=True)
random_text = models.TextField(null=True, blank=True)
I have defined a Company
model which has 2 fields where we are playing around with blank
and null
options. Let’s see what happens with the different fields
-
founded_on
: can receive an emptystring
value at form level (framework/language level). While saving to the database then we would raiseIntegrityError
because the Database will not accept thenull
value due tonull
beingfalse
. -
random_date
: receiving an empty value at form level (Framework) through validation error, since blank is not allowed due toblank
true that is setting constraints at the form level. However, it also allows the column to benull
at the database layer. -
random_text
: This is the option that means that the field is allowed to be saved asnull
at the database layer and also emptystring
value is allowed to be valid data as per the Django forms validation logic due toblank=True
. So in short it can receive empty values (at the framework level and can store empty value at DB level.
To resolve all this confusion consider your Database commit as two layer procedure.
- First, it fill out the form where we can call validate data at the Framework level.
- Second, It has a database-level option that helps in defining DB constraints.
Here blank
is the framework level thing while null
is database level contraint.
- [Django]-How to go from django image field to PIL image and back?
- [Django]-How can I serialize a queryset from an unrelated model as a nested serializer?
- [Django]-How to loop over form field choices and display associated model instance fields