7
votes

There was a nearly similar question: How to make email field unique in model User from contrib.auth in Django

The solution was not perfect: Validating email for uniqueness. The solution provided is rather funny. It disallows modifications to User that leave email intact. How to fix it? Thanks in advance!

3
which of the proposed solutions are you talking about? the accepted solution? - Ofri Raviv
I answered in the other question. I think this one should be closed as it is a complete duplicate. - Ofri Raviv
Which one? Are you sure that question and your answer meet my requirements? Thanks. - Viet
I edited stackoverflow.com/questions/1160030/… and i think it now meets your requirements. - Ofri Raviv
+1 thanks! U earned my vote twice =) Maybe I need a book on Django. There are little details that I miss. - Viet

3 Answers

17
votes

in your __init__.py

from django.contrib.auth.models import User

User._meta.get_field_by_name('email')[0]._unique = True
2
votes

Thanks to Ofri Raviv but what I've seen is not what I needed. So I resolved my own issue and now I'd like to share the tips:

  1. Use username instead of email, exclude email from the form. Mask its label as email.

  2. Subclass User and create a UNIQUE field which receives email addresses, mask it as email, exclude original email field from the form.

It's that simple but took me some time. Hope it help others with the same need.

0
votes

This method won't make email field unique at the database level, but it's worth trying.

Use a custom validator:

from django.core.exceptions import ValidationError
from django.contrib.auth.models import User

def validate_email_unique(value):
    exists = User.objects.filter(username=value)
    if exists:
        raise ValidationError("Email address %s already exits, must be unique" % value)

Then in forms.py:

from django.contrib.auth.models import User
from django.forms import ModelForm
from main.validators import validate_email_unique


class UserForm(ModelForm):
    #....
    email = forms.CharField(required=True, validators=[validate_email_unique])
    #....