我的网址如下所示:
url(r'^register/$', views.register, name='register')
我的views.py中的函数就像:
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.contrib.auth import login, logout, authenticate
from django.contrib.auth.forms import UserCreationForm
def register(request):
"""register"""
if request.method != 'POST':
#we present a blank form
form = UserCreationForm()
else:
#the post the data the users have just filled
form = UserCreationForm(data=request.POST)
if form.is_valid():
new_user = form.save()
# we use the date to redirect our user to the page of login
authenticated_user = authenticate(username=new_user.username,
password=request.POST['password'])
login(request, authenticated_user)
return HttpResponseRedirect(reverse('learning_logs:index'))
context = {'form': form}
return render(request, 'users/register.html', context)
我的register.html:
{% extends "learning_logs/base.html" %}
{% block content %}
<form action="{% url 'users:register' %}" method="post">
{% csrf_token %}
{{ form.as_p }}
<button name="submmit">Register</button>
<input type="hidden" name="next" value="{% url 'learning_logs:index' %}"/>
</form>
{% endblock content %}
当我进行注册时,会出现错误,如MultiValueDictKeyError:“'password'”
有人可以看看并帮我一把吗?非常感谢!
答案 0 :(得分:1)
如果您选中UserCreationForm
,则会看到它没有名为password
的字段,但它有两个:password1
和password2
。您可以将代码更改为:
if form.is_valid():
new_user = form.save()
# we use the date to redirect our user to the page of login
authenticated_user = authenticate(username=new_user.username,
password=form.cleaned_data['password1'])
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
login(request, authenticated_user)
return HttpResponseRedirect(reverse('learning_logs:index'))
但是,您可能希望避免处理密码,只需直接使用login()
,而无需通过authenticate()
:
if form.is_valid():
user = form.save()
login(request, user)
return HttpResponseRedirect(reverse('learning_logs:index'))