Django unique True with blank True


In Django, we can set field with unique=True. But when we want to make the field as optional, we usually think about blank = True which lead to problems. The solution is using default=None

1
email= models.CharField(max_length=255, blank=True, null=True, default=None, unique=True)

And in modelform, we can put this :

1
2
3
# UNIQUE if NOT NULL
def clean_email(self):
    return self.cleaned_data[’email’] or None

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.