无法完成新用户注册。 我在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 = form.save()
login(request, user)
context = {
'user': request.user,
}
return redirect('detail')
context = {
'regist_form': regist_form,
}
return render(request, 'registration/regist.html', context)
在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'
在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>
没有错误发生,当我按下SUBMIT按钮时,它发送detail.html,所以没关系。但是当我看到管理员网站时,没有注册用户。 我真的不明白为什么会发生这种情况。我无法理解什么是错的。我读了Django教程,所以我觉得这种编写代码的方式还可以。我该如何解决这个问题?我该怎么写呢?
答案 0 :(得分:0)
您的表单变量为regist_form
但您尝试保存form
尝试将user = form.save()
更改为user = regist_form.save()
。
您还需要为新用户设置密码,您可以使用commit=False
:
user = regist_form.save(commit=False)
password = regist_form.cleaned_data.get('password')
user.set_password(password)
user.save()
login(request, user)