M
M
Mike2017-03-18 20:02:47
Django
Mike, 2017-03-18 20:02:47

How to check for the existence of an email during registration?

When registering, you need to check for the existence of an email.
I found that this makes the field unique _unique = True but how can I use it in this case.
forms.py

from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User

class RegistrationForm(UserCreationForm):
    email = forms.EmailField(required=True)

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

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
JonGalt, 2017-03-21
@google_online

I have a method in my form:

class RegistrationForm(UserCreationForm):
    email = forms.EmailField(required=True, widget=forms.TextInput(attrs={'placeholder': 'Электронный адрес'}))

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

    # clean email field
    def clean_email(self):
        email = self.cleaned_data["email"]
        try:
            User.objects.get(email=email)
        except User.DoesNotExist:
            return email
        raise forms.ValidationError('Такой адрес электронной почты уже зарегестрирован.')

    # modify save() method so that we can set user.is_active to False when we first create our user
    def save(self, commit=True):
        user = super(RegistrationForm, self).save(commit=False)
        user.username = self.cleaned_data['email']
        user.email = self.cleaned_data['email']
        if commit:
            user.is_active = False  # not active until he opens activation link
        user.save()
        return user

S
sim3x, 2017-03-18
@sim3x

If you find and specify a user in the model, then it will tell you that there is already a user with such an email

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question