V
V
Vlad2021-03-08 23:14:27
Django
Vlad, 2021-03-08 23:14:27

Why does DoesNotExist appear during user registration?

Good afternoon!

I decided here, solely with the help of what I already know on my own, to write a check when registering a user, which, if there is a login in the database, would tell the user that such a login is already taken.
I check on the admin login and everything works, a corresponding message is displayed, but when I try to register a user with any other login I get an error:

Exception Type: DoesNotExist
Exception Value: User matching query does not exist

As far as I understand, this is due to the fact that
User.objects.get(username=request.POST['username'])
does not find the corresponding entry in the database, and this is logical, it cannot be there.
But what I can't understand is why django even climbs into this condition if it if form.is_valid():has already been met.

Here is the view itself with registration and verification:

def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            form.save()
            messages.success(request, 'You have been successfully registered')
            return redirect('login')
        elif User.objects.get(username=request.POST['username']): 
            messages.warning(request, 'Username already exists')
        else:
            messages.error(request, 'Register Error')
    else:
        form = UserCreationForm()
    return render(request, 'news/register.html', {'form':form})


Thank you very much in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2021-03-09
@Vlad1987

learn to debug your code, form.is_valid() returned False

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question