Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django auth.user with unique email

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?

like image 286
Fred Collins Avatar asked Apr 24 '11 23:04

Fred Collins


2 Answers

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.

like image 125
Marek Brzóska Avatar answered Oct 02 '22 22:10

Marek Brzóska


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)
like image 24
mumino Avatar answered Oct 02 '22 22:10

mumino