[Django]-Optional fields in django models

81👍

Add the attribute blank=True. Optionally, you can also make the field NULLable with null=True.

👤mipadi

49👍

Setting null=True for CharField is not recommended, as you can see from django docs:

Avoid using null on string-based fields such as CharField and TextField. If a string-based field has null=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. One exception is when a CharField has both unique=True and blank=True set. In this situation, null=True is required to avoid unique constraint violations when saving multiple objects with blank values.

So I would recommend this configuration:

name = models.CharField(max_length=100, blank=True, default='')

👤Adam

Leave a comment