Home > Software engineering >  How to check if the email/username already exists in the db in django?
How to check if the email/username already exists in the db in django?

Time:09-19

How to check if the email_id/ username already exists in the database in django? I want to check the existence of the email/username in the views rather than in serializer.

Following is the code:

@api_view(['POST'])

def registerUser(request):        
        f_name = request.data.get('f_name')
        l_name = request.data.get('l_name')
        username = request.data.get('username')
        email_id =  request.data.get('email_id')
        password = make_password(request.data.get('password'))
    
        RegistrationRegister.objects.create(
            f_name = f_name, 
            l_name = l_name,
            username = username , 
            email_id = email_id,
            password = password,
            created = datetime.datetime.now().isoformat()
        )
        
        return Response("User registered successfully ")

The name of the table is RegistrationRegister. How can I validate the email and check if it exists in the db?

CodePudding user response:

You can check like that:

username = request.data.get('username')
RegistrationRegister.objects.filter(username=username).exists()

But if it is possible, simply add unique=True to the field you want to be unique.

CodePudding user response:

In RegistrationRegister model add in fields unique=True

  • Related