How to Check Whether a Username Already Exists in Django
In this article, we show how to check whether a username already exists in Django.
When you are creating a signup page, you want to check whether the username that a person enters is taken or not. Of course, on a website, each username has to be unique. There can be no duplicates in username, or else there is no way of distinguishing one user from another. Therefore, when we are creating a signup form, we must check to see that if the username entered is already taken or not.
This is, of course, carried out in the views.py file.
So what we can do is use a try-and-except statement.
When a user enters in a username, we can try to get the username based on the username that the person has entered. If we are able to get it, this means that the username already exists and we must send a message to the person to try another username. If we aren't able to get that username, this means that the username is available and the person can take it.
So let's go to the views.py file and see how this is done.
views.py File
The contents of the views.py file is shown below.
So you see above that we have the statement, user= User.objects.get(username=uservalue)
This statement tries to get the user, where the username is the name entered in by the person signing up.
If the user exists, then we send a message that this username is already taken and to try another username.
If the username is not taken, then the code follows the User.DoesNotExist exception.
The username is then available and the person is signed up with that username.
So this is a sure and simple way to check whether a username is taken or not in Django. If it is taken, then the person gets a message that the username is already taken. If it not taken, then the person gets signed up for that username.
And this is how to check whether a username exists in Django.
Related Resources
How to Randomly Select From or Shuffle a List in Python