7
votes

I use the django.auth system and I've this:

class RegisterForm(UserCreationForm):
    username = forms.RegexField(label= "Username" , max_length = 30, regex = r'^[\w]+$', error_messages = {'invalid': "This value may contain only letters, numbers and _ characters."})
    email = forms.EmailField(label = "Email")
    first_name = forms.CharField(label = "First name", required = False)
    last_name = forms.CharField(label = "Last name", required = False)

    class Meta:
        model = User
        fields = ("username", "first_name", "last_name", "email", )

    def save(self, commit = True):
        user = super(RegisterForm, self).save(commit = False)
        user.first_name = self.cleaned_data["first_name"]
        user.last_name = self.cleaned_data["last_name"]
        user.email = self.cleaned_data["email"]
        if commit:
            user.save()
        return user

I want to set emails as uniques and check the form for this validation. How can I do it?

6

6 Answers

9
votes

add this to your form. But this isn't perfect way. race condition is available by only using this form. I recommend you to add unique constraint at db level.

def clean_email(self):
    data = self.cleaned_data['email']
    if User.objects.filter(email=data).exists():
        raise forms.ValidationError("This email already used")
    return data

SQL to add unique constraint:

ALTER TABLE auth_user ADD UNIQUE (email)
20
votes

Somewhere in your models:

from django.contrib.auth.models import User
User._meta.get_field('email')._unique = True

Notice the underscore before unique. This is where the information is actually held. User._meta.get_field('email').unique is just a @property which looks into it.

This should work for syncdb too, so you will have consistency with the database.

Note too, that from Django 1.5 you will not have to do such things, as User model will be pluggable.

1
votes

I am not sure how to use this, but

from django.contrib.auth.models import User
User._meta.get_field_by_name('email')[0].unique=True

should do it. I guess this goes in your models.py before you run syncdb on the auth model. Bout to try this myself.

0
votes

Overriding the clean() method as suggested by mumimo is described here: http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#overriding-the-clean-method

Ordinarily you could use unique=True on your field definition and then use ModelForm, so that it'll automatically run clean() for all of the fields in your form, but if you're using the django.auth user class you can't modify the fields.

0
votes

You can do the same thing using this in Abstract User Model:

class User(AbstractUser):
...

class Meta:
    unique_together = ('email',)
0
votes

While doing the registration, i found one thing that email is not required in django auth but while simple validation, if we don't provide the email it gives 500 error as we must be checking for the email at the backend.

So to make it required, add to the registrationSerializer;

extra_kwargs = {'email': {'required': True}}

For unique email, other answers are showing that.