简体   繁体   中英

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

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?

Edit : But not sure if I should post this edit into Answer.

Meanwhile, I have found a working workaround by checking if the user exists in the User as an entry. This would go in the form.is_valid() block before working with the form data.

if form.is_valid():
    username = form.cleaned_data['username']
    email = form.cleaned_data['email']          
    if User.objects.filter(username=username).exists() or \
          User.objects.filter(email=email).exists():
        messages.success(request, ('Error: user already exists.'))
        return redirect('auth:home')

Note that in this simplified example I am checking both on user name and email from the form entries:

username = form.cleaned_data['username']
email = form.cleaned_data['email']

My own use case is a bit more complex because the user name is derived from the email and the email contains the company domain. This is why I was looking for some kind of a shortcut .

Have you tried request.user.is_anonymous ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM