Creating New Users

Hi, so I’m in the process for attempting to create new users with information entered into a form. When the call to create a new user is executed I get a POST / account/register 200 response from the server. It seems to have worked…
I have a register function set to redirect to the homepage and it doesn’t work
Lastly, when I login to the admin console nothing is registered.

Im stuck and I’m new, I tried to debug with in VS code and it seems to get stuck in the crispy forms logic and I’m unsure the of the next way to approach this.

from django.urls import path
from . import views

urlpatterns = [
    path('register', views.register, name='register'),
]
from django.shortcuts import redirect, render

from .forms import CreateUserForm

def register(request):

    form = CreateUserForm()

    if request.method == 'POST':

        form = CreateUserForm(request.POST)

        if form.is_valid():

            form.save()

            return redirect('store')
        
    context = {'form':form}

    return render(request, 'account/registration/register.html', context=context)

{% include "store/base.html" %}

{% load static %}

{% load crispy_forms_tags %}

{% block content %}

   <!-- <style>

        body{
            background-color: gray;
        }

    </style> -->

    <body>

        <br>

        <div class="container bg-blue shadow-md p-5 form-layout">

            <h3> Create your account </h3>

            <h5> Purchase Items </h5>

            <br>

            <form method="POST" autocompelte="off">

                {% csrf_token %}

                {{form.username|as_crispy_field}}

                <br>

                {{form.email|as_crispy_field}}

                <br>

                {{form.password1|as_crispy_field}}

                <br>

                {{form.password2|as_crispy_field}}

                <br> <br>

                <button type="submit" class="btn btn-secondary btn-lg w-100 btn-block p-2"> &nbsp; Create Account  </button>

            </form>

        </div>

    </body>

{% endblock %}

Odds are that the form is failing the is_valid test.

What does your CreateUserForm look like?

You might want to ensure that you’re rendering error messages.

You can also do a quick test by simply rendering the form as {{form}} rather than rendering the individual fields, to see what errors are being returned.

Okay, I see, so the POST is returning but, because is_valid() is failing, the form isn’t being saved and redirected.

I was able to track down the issue by putting a breakpoint on is_valid and the model password1 didn’t match the form password1.

Thank you for the guidance, It functions as it should now.

from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User

from django import forms


class CreateUserForm(UserCreationForm):

    class Meta:

        model = User
        fields = ['username', 'email', 'password', 'password2']

    def __init__(self, *args, **kwargs):
        super(CreateUserForm, self).__init__(*args, **kwargs)

        self.fields['email'].required = True #mark email as manditory

    # Email validation to ensure uniqueness

    def clean_email(self):
        email = self.cleaned_data.get("email")

        if User.objects.filter(email=email).exists():
            raise forms.ValidationError('This email is invalid')
        
        if len(email) >= 350:
            raise forms.ValidationError("Your email is too long")
        
        return email