i want email has to be unique

Viewed 69

while creating a new user i want that email has to be uniques for every user by which no user can same email twice

views.py

def register(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')
            email = form.cleaned_data.get('email')
            return redirect('/login/')
    else:
        form = SignUpForm()
    return render(request, 'register.html', {'form': form})

forms.py

class SignUpForm(UserCreationForm):
    first_name = forms.CharField(max_length=30, required=True, help_text='Required.')
    last_name = forms.CharField(max_length=30, required=False, help_text='Optional.')
    email = forms.EmailField(max_length=254, required=True, help_text='Required. Inform a valid email address.')

    class Meta:
        model = User
        fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2',)

but this is not working user got created with same email this is my approach any suggestion

2 Answers

You can check this by implementing a clean_email method in the SignUpForm:

from django.core.exceptions import ValidationError 

class SignUpForm(UserCreationForm):

    # …

    def clean_email(self):
        email = self.cleaned_data['email']
        qs = User.objects.exclude(pk=self.instance.pk).filter(email__iexact=email)
        if qs.exists():
            raise ValidationError('A user with this email address already exists')
        return email

The SignUpForm will run the clean_email method when validating the input. We thus look if there is a User object that has the same email address (we use case insensitve matching), that is not the current object (we exclude pk=self.instance.pk to avoid raising an error in case we update the object).

In case such User exists, we raise a validation error. Django will make sure that this error is attached to the field with the name email since we name the clean method clean_email.

My fist instinct was to implement that at the model level as a constraint.

Related