Home > Blockchain >  Django check user.is_authenticated before UserCreationForm to prevent a user to signup twice
Django check user.is_authenticated before UserCreationForm to prevent a user to signup twice

Time:12-01

In Django, I am trying to prevent an already existing user to register (sign up) again. In my case, the user can sign up with a form. My approach is to check in views.py if the user already exists by checking is_authenticated upfront. If the user does not exist, then the form entries will be processed and the user will be created.

The problem: if the user already exists, I would expect the condition request.user.is_authenticated to be True and the browser to be redirected to home. Instead, the evaluation goes on to process the form throwing (of course) the following error:

Exception Value: duplicate key value violates unique constraint "auth_user_username_key" DETAIL: Key (username)=(john.doe) already exists.

This is a sample of my views.py:

def register_user(request):
    if request.method == "POST":
        if request.user.is_authenticated:
            messages.error(request, ('User already exists.'))
            return redirect('home')
        form = UserCreationForm(request.POST)
        if form.is_valid():
            form.save()
            ... # do more stuff

What am I missing?

CodePudding user response:

Have you tried request.user.is_anonymous?

CodePudding user response:

If the user is already logged in it will raise is_authenticated as True and False it there's no user logged in.

I guess you're trying to register/sign up with no active session, then the first inner if request.user.is_authenticated is evaluated False and not used, so it goes to the second inner if and then the database error is raised because you tried to use the same username.

  • Related