UsercreationForm to check if email exists in database django

I've created a usercreationform and try to check if username and email is already exist in database or not. Here It only check for email if it is exist or not but it cannot check for the username.

Views.py

from django.shortcuts import render,redirect
from . forms import  signupform
from django.contrib import messages
from django.contrib.auth  import login,authenticate,logout
from django.contrib.auth.models  import User


def signup_data(request):
    form = signupform(request.POST)
    if form.is_valid():
                    username = form.cleaned_data['username']
                    email = form.cleaned_data['email']

                    if User.objects.filter(username=username).exists():
                            messages.error(request,'Username is already taken')
                            return redirect('signup')

                        
                    elif User.objects.filter(email=email).exists():
                            messages.error(request,'Email is already taken')
                            return redirect('signup')
                
                    else:
                            form.save()
                            messages.success(request,'Account Is Created')
                            return redirect('signup')
    

    return render(request,'login_module/signup.html',{'form':form, 'message': messages})

Forms.py

from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User  class signupform(UserCreationForm):

    username= forms.CharField(max_length=10,widget=forms.TextInput(attrs={'class':'form-control'}))
    first_name = forms.CharField(max_length=20, widget=forms.TextInput(attrs={'class': 'form-control'}))
    last_name = forms.CharField(max_length=20,widget=forms.TextInput(attrs={'class': 'form-control'}))
    email =  forms.EmailField(max_length=20,widget=forms.EmailInput(attrs={'class': 'form-control'}))
    password1 = forms.CharField(label="Password",widget=forms.PasswordInput(attrs={'class':'form-control'}))
    password2 = forms.CharField(label="Confirm Password",widget=forms.PasswordInput(attrs={'class':'form-control'}))

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

You can combine both the queries to run a OR query using Q for that:

from django.db.models import Q

if User.objects.filter(Q(username=username)|Q(email=email)).exists():
   # do stuff
Back to Top