Form doesn't save :(

I have no idea why it doesn’t save. I get no errors. I checked the logs, but there’s not even a single error. I’ve tried makemigrations and migrate, but it still doesn’t work. The weird thing here is that the User and UserCreationForm method works, but mine doesn’t ._.

I was able to make a message form thing in my last project and I compared the two, but this one just doesn’t work.

This is what I see in my logs when I click the submit button:

[08/Aug/2020 10:16:00] "GET /user/register/ HTTP/1.1" 200 2036
[08/Aug/2020 10:16:07] "POST /user/register/ HTTP/1.1" 302 0
[08/Aug/2020 10:16:07] "GET /dashboard HTTP/1.1" 301 0
[08/Aug/2020 10:16:07] "GET /dashboard/ HTTP/1.1" 200 6897

The user gets redirected to /dashboard when he/she clicks “submit” and if the form is valid.

views.py

from django.shortcuts import render, redirect
from django.contrib import messages

from .forms import RegisterForm
from .models import RegisterModel

def register(request):

    

    if request.method == "POST":

        form = RegisterForm(request.POST or None)

        if form.is_valid():
            form.save()
            messages.success(request, 'account created successfully')
            return redirect('dashboard-home')
    
    else:
        form = RegisterForm()
        
    return render(request, 'login/registration/registration.html', {'form':form})

forms.py

from django import forms
from .models import RegisterModel

class RegisterForm(forms.ModelForm):
    
    class Meta:
        model = RegisterModel
        fields = '__all__'
        widgets = {
            'password': forms.PasswordInput()
        }

models.py

from django.db import models
from django.core.exceptions import ValidationError

class RegisterModel(models.Model):
    username = models.CharField(max_length=32, unique=True)
    email = models.EmailField()
    password = models.CharField(max_length=256)
    # confirm_password = models.CharField(max_length=256)
    
    def __str__(self):
        return self.username

registration.html

<div id="registration-div">

    <div id="registration-form-split"></div>
    <div id="registration-form-div">
        <h1 id="registration-form-header">Register</h1>

        <form method="POST" id="registration-form">
            {% csrf_token %}
            {{form|crispy}}
            <button id="registeration-button">Register</button>
        </form>

    </div>

</div>

Just to correct one statement, you wrote that the user gets redirected if the form is valid. That is incorrect. Based upon the indentation levels of your code, the redirect is outside the if condition, and will occur regardless of the validity of the form.

Ken

1 Like

It still doesn’t work :confused:

I changed form part to

if request.method == "POST":

        form = RegisterForm(request.POST or None)

        if form.is_valid():
            form.save()
            messages.success(request, 'account created successfully')
            return redirect('dashboard-home')
    
    else:
        form = RegisterForm()

When I refresh the admin panel, it says, " * Account created successfully". When I try to register another account with the same username, I can’t because it has the unique attribute set to True and it says a model with that name already exists.

P.S. I added the unique=True attribute after I posted this post.

If you’re getting the error about the account being non-unique, then your form is being saved. Use the admin to look at the table to verify that.

However, I’m guessing the real issue is that you can’t log on using that account. If so, that’s because you’re saving a plain text password in the database, when Django expects the passwords to be stored hashed.

1 Like

My problem is that none of the things I submit save. I always use a new username every time I do it.

I’m sorry, I’m having a hard time reconciling these two statements.

Can you be more specific as to what type of test you’re running, what you’re entering, what you’re seeing as the results and how is it different from what you’re seeing?

Also, it’s going to be helpful to see the complete models, forms, and views involved here.
(I’m assuming there’s no JavaScript involved, so the segment of the template you’ve provided should be sufficient.)

Ken

1 Like

I did the whole thing over again and followed a tutorial created by Tech with Tim. This is what my code looks like now:

from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django import forms
from django.core.exceptions import ValidationError

class RegisterForm(forms.Form):
    username = forms.CharField(label='Enter Username', min_length=4, max_length=150)
    email = forms.EmailField(label='Enter email')
    password1 = forms.CharField(label='Enter password', widget=forms.PasswordInput)
    password2 = forms.CharField(label='Confirm password', widget=forms.PasswordInput)

    def clean_username(self):
        username = self.cleaned_data['username'].lower()
        r = User.objects.filter(username=username)
        if r.count():
            raise  ValidationError("Username already exists")
        return username

    def clean_email(self):
        email = self.cleaned_data['email'].lower()
        r = User.objects.filter(email=email)
        if r.count():
            raise  ValidationError("Email already exists")
        return email

    def clean_password2(self):
        password1 = self.cleaned_data.get('password1')
        password2 = self.cleaned_data.get('password2')

        if password1 and password2 and password1 != password2:
            raise ValidationError("Password don't match")

        return password2

    def save(self, commit=True):
        user = User.objects.create_user(
            self.cleaned_data['username'],
            self.cleaned_data['email'],
            self.cleaned_data['password1']
        )
        return user

I removed the model.

Edit: Forgot to tell that it works now. Also, regarding the method I used before this, it worked, but I just forgot to register RegisterModel in admins.py. Lol.