密码不会保存在新用户注册中。我在views.py中写道
def regist(request):
regist_form = RegisterForm(request.POST or None)
context = {
'regist_form': regist_form,
}
return render(request, 'registration/regist.html', context)
@require_POST
def regist_save(request):
regist_form = RegisterForm(request.POST)
if regist_form.is_valid():
user = regist_form.save(commit=False)
password = regist_form.cleaned_data.get('password')
user.set_password(password)
user.save()
login(request, user)
context = {
'user': request.user,
}
return redirect('detail')
context = {
'regist_form': regist_form,
}
return render(request, 'registration/regist.html', context)
在 regist.html
中
<div class="heading col-lg-6 col-md-12">
<h2>New account registration</h2>
<form class="form-horizontal" action="regist_save/" method="POST">
<div class="form-group-lg">
<label for="id_username">username</label>
{{ regist_form.username }}
</div>
<div class="form-group-lg">
<label for="id_email">email</label>
{{ regist_form.email }}
</div>
<div class="form-group-lg">
<label for="id_password">password</label>
{{ regist_form.password1 }}
</div>
<div class="form-group-lg">
<label for="id_password">password(conformation)</label>
{{ regist_form.password2 }}
<p class="help-block">{{ regist_form.password2.help_text }}</p>
</div>
<div class="form-group-lg">
<div class="col-xs-offset-2">
<button type="submit" class="btn btn-primary btn-lg">SUBMIT</button>
<input name="next" type="hidden"/>
</div>
</div>
{% csrf_token %}
</form>
</div>
forms.py 中的
class RegisterForm(UserCreationForm):
class Meta:
model = User
fields = ('username', 'email','password1','password1',)
def __init__(self, *args, **kwargs):
super(RegisterForm, self).__init__(*args, **kwargs)
self.fields['username'].widget.attrs['class'] = 'form-control'
self.fields['email'].widget.attrs['class'] = 'form-control'
self.fields['password1'].widget.attrs['class'] = 'form-control'
self.fields['password2'].widget.attrs['class'] = 'form-control'
用户名&amp;电子邮件正常注册。所以我真的不明白为什么密码没有注册。我读了Django教程,我觉得我的代码还可以。
我该如何解决这个问题?我该怎么写呢?
答案 0 :(得分:2)
您的表单包含字段password1
和password2
,而不是password
和regist_form.cleaned_data.get('password')
返回无。
因此,您应该将password1
字段重命名为password
:
class RegisterForm(UserCreationForm):
class Meta:
model = User
fields = ('username', 'email','password', 'password2',)