Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using Default UserCreationForm does not show error if the passwords do not match

Using Default UserCreationForm from django.contrib.auth.forms does not show error if the passwords do not match. I do not want to create a custom model.

Here is the code from my views.py file

from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render

# Create your views here.
def register(response):
    if response.method == "POST":
        print(response.POST)
        form = UserCreationForm(response.POST)
        if form.is_valid():
            form.save()
        else:
            print(form.errors)

    form = UserCreationForm()
    return render(response,"register/register.html",{"form":form})

register.html code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<html> 
    <head>
        <title>Register </title>    
    </head>
    <body> 
        <h1>This is the Registration page</h1>
        <form method="post">
            {% csrf_token %}
            {{form.as_p}}
            <button type="submit">Submit</button>
        </form>
    </body>
</html>

I thought the message would be automatically displayed. Am I missing something?
Edit: None of the error message are being displayed like password length < 8, all numeric passwords, etc.

>Solution :

You each time create a new form, you should render the one that is invalid:

from django.shortcuts import redirect


def register(response):
    if response.method == 'POST':
        form = UserCreationForm(response.POST)
        if form.is_valid():
            form.save()
            return redirect('name-of-some-view')
    else:
        form = UserCreationForm()  # 🖘 only for a GET request
    return render(response, 'register/register.html', {'form': form})

Note: In case of a successful POST request, you should make a redirect
[Django-doc]

to implement the Post/Redirect/Get pattern [wiki].
This avoids that you make the same POST request when the user refreshes the
browser.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading