Explain the difference between null=True and blank=True in Django Python
In this tutorial, I will teach you the difference between null=true and blank=true in Django Python.
Many times we have come across these names while declaring models but often don’t know what that means let’s check it out.
So, today let’s discuss an interesting topic and that will be the most useful for a developer to distinguish the difference whenever they use it again in the future.
In Django Python, explain the difference between null=True and blank=True
- Let’s learn briefly this topic with example,
from django.db import models class Book(models.Model): name=models.CharField(max_length=15) author=models.CharField(max_length=15) about=models.TextField(blank=True) # if you leave blank then raises IntegrityError publish_date=models.DataField(null=True,blank=True) # here null is allowed, however, it must be completed in a form.
- Here, In the models.py, I have to define a simple ambiguous book model where we have the following fields name, author, and publish date.
- Here, the about is a TextField in which blank has been set to True and in published_date (DataField) – Null has been set to True.
- For programmers, these terms are often a bit confusing and used incorrectly so what is even mean?
- Well, when we have to set blank=True we essentially mean that while saving the model we don’t require to provide any legitimate value to it. whereas when we are setting null=True that would mean that we have provided it a Null value.
- Now if this sounds confusing then it is you can simply think of it as that the about field does not require to have any value whereas, in publishing date we have value.
- Now next question that might come in your into your mind is how can an integer have no value, how can a variable has no value I mean of course they must be some default value when we are entering it truly is the case and initially some default value is provided.
- However, that is the case when the field is something like integer, float, character, or anything whereas in a field like the text, it is not the case this is where the correct use of null and blank comes into the picture if you are using or making a field that may have a garbage value make sure to initialize it or at least set Null=True so that it does not lead to any runtime errors while running the program in case the user forgot to enter a value.
- Whereas in fields like a text where the user may or may not want to provide an input it is advised that you enter blank is equal to true
- Apart from this, you should also know that blank and null are regarded as false if they are encountered in a statement like those of conditions
- For example, if statement, while statement, and so on.