2
\$\begingroup\$

Can you say, is this a bad code for registration in Django? Do I need to fix something or use a pip instead? (I am learning)

def register(request):

    error_messages = {}

    if request.POST:
        form = UserCreationForm(request.POST)

        if form.is_valid():
            new_user = form.save()

            user = authenticate(username=request.POST["username"], password=request.POST["password1"])
            login(request, user)

            return redirect('index')
        else:
            form = UserCreationForm()
            return redirect('register')

    return render(request, 'account/register.html',
            {'title': 'Registration', 'error_messages': error_messages})
\$\endgroup\$
1
\$\begingroup\$

From what you can find on the docs you are pretty close. I may change a couple things a little just to be on the safe side:

Change:

user = authenticate(username=request.POST["username"], password=request.POST["password1"])

To:

user = authenticate(username=form.cleaned_data['username'], form.cleaned_data['password1'])

The first way is not wrong, but using validated data on forms is a better practice than using the raw post request. Is better to be consistent.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.