Home > Mobile >  Django Registration - Checks if a user already exists
Django Registration - Checks if a user already exists

Time:02-11

The web app currently should be able to register new users. However, should a user already exists, it should redirect user to the login page with a message of "User already exists!".
The Django views:

from django.contrib.auth.models import User

def registerPage(request):
     form = CreateUserForm()

    if request.method == 'POST':
        form = CreateUserForm(request.POST)
        if form.is_valid():
            email = form.cleaned_data['email']
            username = form.cleaned_data['username']
            if User.objects.filter(username=username).exists():
                messages.info(
                    request, 'User already exists! Try logging in.')
                return redirect('login')
            else:
                user = form.save(commit=False)
                raw_password = User.objects.make_random_password()
                user.set_password(raw_password)
                user.save()
                ...

I filter the user by his/her username and checks if it already exists by using the exists() method. This doesn't seem to work though. Is there something I'm missing?

UPDATE
What's not working is that the check I believe is not working. Because if it successfully checks that a user exists, then it should redirect('login') instead of running the else statement.


SOLUTION
Turns out that because I'm using Django's built in CreateUserForm and is doing validation using form.is_valid(), hence it is already built in for Django to check whether the user already exists or not. So what I did was to just add an else statement after the if form.is_valid() and redirect my user to the login page.

CodePudding user response:

username already marked unique=True in auth/models.py so simply you can use try/catch.

  • Related