0
votes

With this setup, the password isn't stored when someone submits the form on the register page. However, the username and email are stored. Everything displays accurately, with 'password1' and 'password2' linking to a "Password" and "Password confirmation" input field in the web page. Using the default UserCreationForm instead works fine. Does anyone know what code I'm missing?

forms.py:

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

class MyRegistrationForm(UserCreationForm):
    email = forms.EmailField(required=True)

    class Meta:
        model = User
        fields = ['username', 'email', 'password1', 'password2']

    def save(self, commit=True):
        user = super(UserCreationForm, self).save(commit=False)
        user.email = self.cleaned_data['email']

        if commit:
            user.save()

        return user

views.py:

from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.contrib import auth
from django.core.context_processors import csrf
from mainsite.forms import MyRegistrationForm

...

def register_user(request):
    if request.method == 'POST':
        form = MyRegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/accounts/register_success')
    args = {}
    args.update(csrf(request))

    args['form'] = MyRegistrationForm()

    return render_to_response('directory/register.html', args)

def register_success(request):
    return render_to_response('directory/register_success.html')

register.html:

{% extends "directory/base.html" %}

{% block content %}

<h2>Register</h2>
<form action="/accounts/register/" method="post">{% csrf_token %}
    {{ form }}
<input type="submit" value="register" />

</form>

{% endblock %}
2

2 Answers

1
votes

Try this:

user.email = self.cleaned_data['email']
user.set_password(self.cleaned_data['password1'])
user.save()
2
votes

I am dealing with the exact same code from Mike Hibbert's Django tutorials. This question was also answered here: django - no password set after successful registration

When you save the form, call super on MyRegistrationForm instead of UserCreationForm:

def save(self, commit=True):
    user = super(MyRegistrationForm, self).save(commit=False)
    ...