[SOLVED] How to check if the email/username already exists in the db in django?

Issue

This Content is from Stack Overflow. Question asked by Ritika

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?



Solution

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.


This Question was asked in StackOverflow by Ritika and Answered by NixonSparrow It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?