django中的MultiValueDictKeyError

时间:2015-02-15 11:52:45

标签: python django

嗨,我想在django中制作一个注册页面 -

我的views.py -

from django.shortcuts import render, redirect
from django.http import HttpResponseRedirect

def home(request):
    if request.method == 'POST':
        post = request.POST
        if 'signup' in post:
            return HttpResponseRedirect('/wall/signup')
    return render(request, 'wall/home_page.html')

def signup(request):
    if request.method == 'POST':
        post = request.POST
        username = post['username']
        password = post['password']
        return success(request, username)
    return render(request, 'wall/signup.html')

def success(request, name):
    if request.method == 'POST':
        post = request.POST
        if 'home' in post:
            return HttpResponseRedirect('/wall')
    return render(request, 'wall/success_page.html', {'name': name}) 

和我的success_page.html -

<html>
    <body>
        Success {{ name }}
        <form id="form" method="post">
            {% csrf_token %}
            <button type="submit" name="home">
                Home
            </button>
        </form>
    </body>
</html>

但是当我点击“主页”按钮时,它会出错 -

MultiValueDictKeyError at /wall/signup/

"'username'"

我认为行 - username = post['username']正在发出此错误

我不知道如何解决它,我甚至不知道为什么我会收到此错误。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

<form>中的success_page.html标记没有action属性,因此您点击Home按钮将表单发送回{{1}查看。

您应该更改signup()视图以重定向到成功视图,而不是返回signup()的结果:

success()

def signup(request): if request.method == 'POST': ... return redirect('signup_success', username) 是指向signup_success视图的网址名称。

success()

或者,也可以将urlpatterns = patterns('', ... url(r'^success/(?P<name>\w+)/$', views.success, name='signup_success'), ... ) 属性添加到action

success_page.html