'Django-registration - How to check if email exists in database

During registration currently when a user is entering an existing username and an email it is notified that this username already exists in database. When the user enters a different username but an email that exists then user is created successfully in db. So i want to validate if email exists in database. For this reason i've created the following but unfortunately it does not work as expected, (user is created if same email exists).

forms.py file

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


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

    class Meta:
        model = User
        fields = ['username', 'email', 'password1', 'password2']

def clean_email(self):
    # Get the email
    email = self.cleaned_data.get('email')
    if User.objects.filter(email__iexact=email).exists():
        raise forms.ValidationError("User with that email already exists")
    return email

views.py file

from django.shortcuts import render
from django.contrib.messages.views import SuccessMessageMixin
from django.views import generic
from django.contrib.auth.forms import UserCreationForm
from django.urls import reverse_lazy


from .forms import SignupForm


class UserRegisterView(SuccessMessageMixin, generic.CreateView):
    form_class = SignupForm
    template_name = 'registration/register.html'
    success_url = reverse_lazy('login')
    success_message = "Hello %(username)s! Your account has been created"

Thank you for your time.



Solution 1:[1]

Because you took email as a dictinobary <'dict' object is not callable> so, as a list. It is working on my project

email = self.cleaned_data.get['email']

def clean_email(self):
    # Get the email
    email = self.cleaned_data.get['email']
    if User.objects.filter(email__iexact=email).exists():
        raise forms.ValidationError("User with that email already exists")
    return email

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jasurbek Odilov