Check User's Email Existence.
There is an issue I faced in Django when I create a new user with an email that in use by another user it doesn't throw an error, and it allows you have multiple users with the same email!
This can cause many issues in your website for example when a user reset his password to get a reset link sent to his email.
Don't worry you will learn how to fix that now.
As we already created a custom user model in our last post, we can easy now fix this issue.
if you didn't read last post read it here
in the users app create a forms.py file and we will create new forms with a validation to check if the email exists.
we will override django's defult user forms UserChangeForm and UserCreationForm so we gonna import them first.
# forms.py
from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserChangeForm, UserCreationForm
User = get_user_model()
Note: we imported get_user_model to get the user model, this function is getting the user model declared in AUTH_USER_MODEL variable in settings.py file.
so if you have a custom user model and declared it in settings it will get it, if now it will get the default django user model.
Now we will override the clean_email function to add our validation
class CustomUserCreationForm(UserCreationForm):
def clean_email(self):
email = self.cleaned_data['email']
if email:
match = User.objects.filter(email=email))
if match:
raise forms.ValidationError('This email address is already in use')
return email
class Meta:
model = User
fields = ('username', 'email', 'image')
class CustomUserChangeForm(UserChangeForm):
def clean_email(self):
email = self.cleaned_data['email']
if email:
match = User.objects.filter(email=email).exclude(id=self.instance.pk)
if match:
raise forms.ValidationError('This email address is already in use')
return email
Note: in the UserChangeForm we used exclude to exclude the user that we are changing its email, to avoid raising the validation error if we didn't change the email and just updated other data.
Now we need to add our custom forms to our CustomUserAdmin that we created in admin.py last post.
as we are using UserAdmin class it has 2 variables add_form and form, we will override them with our forms.
# admin.py
from .forms import CustomUserChangeForm, CustomUserCreationForm
@admin.register(User)
class CustomUserAdmin(UserAdmin):
add_form = CustomUserCreationForm
form = CustomUserChangeForm
...
# the rest of the code
That's it! now we will see the error message we made when we try to add new user with an existing email.
I hope the tutorial was simple.
Feel free to reach out if you have any questions.
Join to discord Server Here - Django Learn Together.
Views: 529