+

null = True — inline field validation in Django

Syntax

 field_name = models.Field (null = True) 

Django embedded field validation null = True Explanation

Illustration of null = True using the example. Consider a project named pythonengineering that has an application named geeks .

Refer to the following articles to check how to create a project and an app in Django.

Enter the following code into the models.py file of the geeks application. We will use CharField to experiment with all the margin variations.

from django.db import models

from django.db.models import Model

# Create your models here.

  

class GeeksModel (Model):

geeks_field = models.CharField (max_length = 200 , null = True  )

After running makemigrations and migrating to Django and rendering the above model, let`s try creating an instance using None from the Django shell. To start the Django shell, enter the command,

 Python manage.py shell 

Now let`s try to create a GeeksModel instance using None .

# import the required model

from geeks. models import GeeksModel

  
# instantiate GeeksModel

s = GeeksModel.objects.create (geeks_field = None )

 
# save the current instance of the model
s.save ()

Let`s check in the admin interface to see if the model has been instantiated. 

Therefore null = True changes the field to accept values ​​ NULL or in terms of Python None Values.

Advanced Concepts with null = True

Avoid empty values ​​ in no data ": NULL and empty string . In most cases, it is redundant to have two possible values ​​for "no data"; Django`s convention is to use an empty string, not NULL. The only exception is when the CharField is unique = True and empty = True . In this situation, null = True is required to avoid unique constraint violations when storing multiple objects with null values.

For both string and non-string fields, you must also set blank = True if you want to allow blank values ​​in forms, since a null parameter only affects the database storage (see blank).

Get Solution for free from DataCamp guru