Django unique, null and blank CharField giving ‘already exists’ error on Admin page

None of the answers clearly describe the root of the problem.

Normally in the db you can make a field null=True, unique=True and it will work… because NULL != NULL. So each blank value is still considered unique.

But unfortunately for CharFields Django will save an empty string "" (because when you submit a form everything comes into Django as strings, and you may have really wanted to save an empty string "" – Django doesn’t know if it should convert to None)

This basically means you shouldn’t use CharField(unique=True, null=True, blank=True) in Django. As others have noted you probably have to give up the db-level unique constraint and do your own unique checks in the model.

For further reference, see here: https://code.djangoproject.com/ticket/4136
(unfortunately no good solution decided at time of writing)

NOTE:
As pointed out by @alasdair in a comment, that bug has now been fixed – since Django 1.11 you can use CharField(unique=True, null=True, blank=True) without having to manually convert blank values to None

Leave a Comment

tech