noahandthewhale noahandthewhale - 4 months ago 30
Python Question

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

I've been getting the most weird error ever. I have a Person model

class Person(models.Model):
user = models.OneToOneField(User, primary_key=True)
facebook_id = models.CharField(max_length=225, unique=True, null=True, blank=True)
twitter_id = models.CharField(max_length=225, unique=True, null=True, blank=True)
suggested_person = models.BooleanField(default=False)


I recently added the twitter_id field. When I access the Django admin page, and try to change the 'person' into a suggested_person, I get the following error:

Person with this Twitter id already exists.


I find this error to be extremely strange because the Facebook_id field is designed the exact same way as the Twitter_id field.

What could be the reason for this?

Answer

Since you have null=True, blank=True and unique=True, django is considering None or blank as a unique entry. Remove the unique constraint and handle the uniqueness part in the code.