使用此设置,当有人在注册页面上提交表单时,不会存储密码。但是,存储用户名和电子邮件。一切都准确显示,密码1'和密码2'链接到"密码"和#34;密码确认"网页中的输入字段。使用默认的UserCreationForm可以正常工作。有谁知道我错过了什么代码?
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 %}
答案 0 :(得分:1)
我正在处理Mike Hibbert的Django教程中完全相同的代码。这个问题在这里也回答了: django - no password set after successful registration
保存表单时,请在MyRegistrationForm而不是UserCreationForm上调用super:
def save(self, commit=True):
user = super(MyRegistrationForm, self).save(commit=False)
...
答案 1 :(得分:0)
试试这个:
user.email = self.cleaned_data['email']
user.set_password(self.cleaned_data['password1'])
user.save()