Ahmed Yasin
Ahmed Yasin

Reputation: 948

How to check email is already in database or not in django?

I want to add a functionality in registration form that if email is already in database than display massage ie this email is already register. i am trying this with the following code but this is not working

accounts/forms.py

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


class UserCreateForm(UserCreationForm):

    # email = forms.EmailField()
    class Meta:
        fields = ["username","email","password1","password2"]
        model = get_user_model()
        
    def clean_email(self):
            email = self.cleaned_data.get('email')
            if email in User.objects.all():
                raise forms.ValidationError("This email is already register")
            return email
    def __init__(self,*args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['username'].label = 'Display Name'
        # self.fields['email'].label = 'Email Address'

Upvotes: 1

Views: 364

Answers (2)

alamshafi2263
alamshafi2263

Reputation: 659

in your UserCreateForm.clean_email you are not checking it the correct way. You are checking by this if email in User.objects.all(). Here the email is not a a User object. User.objects.all() returns a queryset of User objects. Since, email is not an instance of User your condition checking is not successful. Rather do the following to check if an user already exists with the provided email

def clean_email(self):
    email = self.cleaned_data.get('email')
    if email.split('.')[-1] !=  'edu' :
        raise forms.ValidationError("Only .edu email addresses allowed")
    if User.objects.filter(email__iexact=email).exists():
        raise forms.ValidationError("User with that email already exists")
    return email

Make sure you set email in your User model to be unique.

Upvotes: 2

JPG
JPG

Reputation: 88519

You are running the validation in wrong way, it should be as,

class UserCreateForm(UserCreationForm):
    # rest of your code

    def clean_email(self):
        email = self.cleaned_data["email"]
        if User.objects.filter(email__iexact=email).exists():
            raise forms.ValidationError("Only .edu email addresses allowed")
        return email

Upvotes: 1

Related Questions