In this Python Django Tutorial, we will discuss a Django error that is generally faced by developers while creating a Django project. We will see the reasons for the occurrence of this Django IntegrityError so that we can avoid those mistakes in future projects and we will also learn how to fix this error.
We will discuss the reasons for the occurrence of Django IntegrityError and how to fix Django IntegrityError.
Solve Django Integrity Error :
In the above picture, the IntegrityError is showing that the column “working_till” cannot be null. Recently while building a Job Portal through Django, I faced this IntegrityError.
See the code in the below image to understand where was the mistake.
On the above field “working_till” :
working_till = models.DateTimeField(blank=True)
- We have added
blank=Trueto the field, but not
null=True. This means that your DB is expecting that field to have a value. So when it doesn’t you get an error.
Let’s understand what happens when the field is set to null and blank
In the case of Null :
- If True, Django will store empty values as NULL in the database. The default is False. Note that empty string values will always get stored as empty strings, not as NULL. Only use null=True for non-string fields such as integers, booleans, and dates. For both types of fields, you will also need to set blank=True if you wish to permit empty values in forms, as the null parameter only affects database storage.
In the case of blank :
- When True, the field is allowed to be blank. The default is False.
Note that this is different than null which is purely database-related, whereas blank is validation-related. If a field has blank=True, form validation will allow the entry of an empty value. If a field has blank=False, the field will be required.
In this Python Django tutorial, we learn about Django Integrity errors. We have learned how to fix this error and we also come to know about the reasons for its occurrence.
We also learned about the Null and True fields of Django and had a good understanding of its implementation.
You may also like to read the following articles:
- Python Django “Template does not exist” error
- Order a Query in descending and ascending in Python Django
- Django Programming Error Column does not exist.
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.