integrity error in django

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.

integrity error in django

We will discuss the reasons for the occurrence of Django IntegrityError and how to fix Django IntegrityError.

integrity error in django

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 image below to understand where the mistake was.

Python Django Integrity Error
Python Django Integrity Error


On the above field “working_till” :

working_till = models.DateTimeField(blank=True)
  • We have added blank=True to 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.
READ:  Python Django concatenate string

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.

Conclusion:

In this Python Django tutorial, we learn about Django Integrity errors. We learn how to fix this error “integrity error in django”.

You may also like to read the following articles: