在登录页面POST请求后Django中生成MultiValueDictKeyError [英] MultiValueDictKeyError generated in Django after POST request on login page

查看:505
本文介绍了在登录页面POST请求后Django中生成MultiValueDictKeyError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试建立一个登录页面。我正在运行Django 1.6.1。我在很大程度上遵循了本教程,网址为www.fir3net.com/Django/django.html。



错误消息:

 请求方法:GET 
请求URL:http://127.0.0.1:8000/login/

正在使用的数据库:SQLite3

Django版本: 1.6.1
Python版本:2.7.4
已安装的应用程序:
('django.contrib.admin',
'django.contrib.auth',
' django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django。
安装的中间件:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware' ,
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.RemoteUserMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'd jango.middleware.clickjacking.XFrameOptionsMiddleware')


追溯:
文件/usr/local/lib/python2.7/dist-packages/django/core/handlers/ base.pyin get_response
114. response = wrapped_callback(request,* callback_args,** callback_kwargs)
文件/ home / tatenda / Documents / Programming / Django / Progs / django_bookmarks / bookmarks / views。 pyin login_user
17. username = request.POST ['username']
文件/usr/local/lib/python2.7/dist-packages/django/utils/datastructures.py中__getitem__
301. raise MultiValueDictKeyError(repr(key))

异常类型:/ login /
处的MultiValueDictKeyError异常值:'username'

查看代码(我知道这里调用的几个导入函数对我的直接问题来说是多余的。大多数情况下,它们是尝试遵循以前有关如何执行此操作的教程的冗余代码):

  from django.http import * 
从django.shortcuts import render_to_response,重定向
从django.template导入RequestContext
从django.template import上下文
从django.template.loader import get_template
从django.http导入HttpResponse,Http404
从django.contrib.auth.models导入用户
从django.contrib.auth导入验证,登录,注销
从django.views.decorators.csrf导入csrf_exempt,csrf_protect
from django.contrib.auth.decorators import login_required

def login_user(request):

username = password =''
username = request。 POST ['username']
password = request.POST ['password']
user = authenticate(username = username,password = password)
如果用户不是None:
如果user.is_active:
login(request,user)
返回HttpResponseRedirect('/ main_page /')
返回render_to_response('base.html',context_instance = RequestContext(request))

@login_required(login_url ='/ login /')
def main_page(request):
template = get_template('main_page.html')
variables = Context({
'head_title':'Django Bookmarks',
'page_title ':'欢迎来到Django书签',
'page_body':'存储和共享书签的位置'
})
output = template.render(variables)
return HttpResponse (输出)

def user_page(请求,用户名):
try:
user = User.objects.get(username = username)
除了:
raise Http404('Requested user not found。')

bookmarks = user.bookmark_set.all()
template = get_template('user_page.html')
variables =上下文({
'username':username,
'bookma rks':bookmarks
})
output = template.render(variables)
return HttpResponse(output)

@csrf_exempt
def login_page(request) :

username = request.POST ['username']
password = request.POST ['password']
user = authenticate(username = username,password = password)
如果用户不是无:
如果user.is_active:
登录(请求,用户)
template = get_template('main_page.html')
variables = Context( {
'head_title':'Django Bookmarks',
'page_title':'欢迎来到Django书签',
'page_body':'你在哪里存储和共享书签'
})
output = template.render(variables)
return HttpResponse(output)
else:
raise Http404('禁用帐号,请联系管理员')
else:
提高Http404(无效登录)

来自urls.py文件的信息:

$从django.conf.urls导入模式,包含来自django.contrib的url
导入admin
从bookmarks.views导入b
$ b

  * 

admin.autodiscover()

urlpatterns = patterns('',
(r'^ $',main_page),
(r' ^ user /(\w +)/ $',user_page),
url(r'^ login / $',login_user),

pre>

用于创建登录页面的基本模板(文件名为base.html):

注意 CSS样式是基于引导的

 <!DOCTYPE html> 
< html>
< head>
{%block head%}
< link rel =stylesheethref =style.css/>
< title> {%block title%} {%endblock%} - 我的网页< / title>< / div>
{%endblock%}
< / head>
< body>
< div id =content> {%block content%} {%endblock%}< / div>
< div id =footer>
{%block footer%}
& copy;版权所有2011 by< a href =http://domain.invalid/>你< / a>
{%endblock%}
< / div>
< / body>
< / html>

登录页面的HTML代码(该文件名为login.html):

  {%extendsbase.html%} 
{%block main%}
< div id =login >
< form class =form-horizo​​ntalname =LoginFormaction =/ login /method =post>
{%csrf_token%}
{%if next%}
< input type =hiddenname =nextvalue ={{next}}/>
{%endif%}
< div class =control-group>
< label class =control-labelfor =username>用户名< / label>
< div class =controls>
< input type =textid =usernameplaceholder =Username>
< / div>
< / div>
< div class =control-group>
< label class =control-labelfor =password> Password< / label>
< div class =controls>
< input type =passwordname =passwordid =passwordplaceholder =Password>
< / div>
< / div>
< div class =control-group>
< div class =controls>
< button type =submitclass =btn>登录< / button>
< / div>
< / div>
< / form>
< / div>
{%endblock%}


解决方案

同样的错误,我做到了这一点,它的工作。
更改:

  username = request.POST ['username'] 
password = request.POST [ '密码']

to:

  username = request.POST.get('username')
password = request.POST.get('password')

以上处理可能导致的POST和GET方法。
我希望这有帮助。


I'm trying to build a login page. I'm running Django 1.6.1. I've largely been following the tutorial at www.fir3net.com/Django/django.html. For convenience I will repost a lot of it here.

Error Message:

Request Method: GET
Request URL: http://127.0.0.1:8000/login/

Database In Use: SQLite3 

Django Version: 1.6.1
Python Version: 2.7.4
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.contenttypes',
 'bookmarks')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.RemoteUserMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware')


Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
  114.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/tatenda/Documents/Programming/Django/Progs/django_bookmarks/bookmarks/views.py" in login_user
  17.   username = request.POST['username']
File "/usr/local/lib/python2.7/dist-packages/django/utils/datastructures.py" in __getitem__
  301.             raise MultiValueDictKeyError(repr(key))

Exception Type: MultiValueDictKeyError at /login/
Exception Value: "'username'"

View Code (I understand that several of the import functions called here are superfluous to my immediate problem. Mostly they are redundant code from trying to follow previous tutorials on how to do this):

from django.http import*
from django.shortcuts import render_to_response, redirect
from django.template import RequestContext
from django.template import Context
from django.template.loader import get_template
from django.http import HttpResponse, Http404
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from django.contrib.auth.decorators import login_required

def login_user(request):

    username = password = ''
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(username=username, password = password)
    if user is not None:
        if user.is_active:
            login(request, user)
            return HttpResponseRedirect('/main_page/')
    return render_to_response('base.html', context_instance = RequestContext(request))

@login_required(login_url = '/login/')
def main_page(request):
    template = get_template('main_page.html')
    variables = Context ({
        'head_title':'Django Bookmarks',
        'page_title':'Welcome to Django Bookmarks',
        'page_body':'Where you store and share bookmarks!'
    })
    output = template.render(variables)
    return HttpResponse(output)

def user_page(request, username):
    try:
        user = User.objects.get(username=username)
    except:
        raise Http404('Requested user not found.')

    bookmarks = user.bookmark_set.all()
    template = get_template('user_page.html')
    variables = Context({
        'username':username,
        'bookmarks': bookmarks
    })
    output = template.render(variables)
    return HttpResponse(output)

@csrf_exempt
def login_page(request):

    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(username=username, password=password)
    if user is not None:
        if user.is_active:
            login(request,user)
            template = get_template('main_page.html')
            variables = Context ({
                'head_title':'Django Bookmarks',
                'page_title':'Welcome to Django Bookmarks',
                'page_body':'Where you store and share bookmarks!'
            })
            output = template.render(variables)
            return HttpResponse(output)
        else:
            raise Http404('Disabled account, please contact administrator.')
    else:
        raise Http404('Invalid login.')

Info from urls.py file:

from django.conf.urls import patterns, include, url
from django.contrib import admin
from bookmarks.views import*

admin.autodiscover()

urlpatterns = patterns('',
    (r'^$', main_page),
    (r'^user/(\w+)/$', user_page),
    url(r'^login/$', login_user),
)

Base Template Used to Create Login Page (the file is named base.html):
Note - the CSS styling is bootstrap based

<!DOCTYPE html>
<html>
    <head>
        {% block head %}
            <link rel = "stylesheet" href = "style.css" />
            <title> {% block title %}{% endblock %} - My Webpage</title></div>
        {% endblock %}
    </head>
    <body>
        <div id = "content">{% block content %}{% endblock %}</div>
        <div id = "footer">
            {% block footer %}
                &copy; Copyright 2011 by <a href="http://domain.invalid/">you</a>
            {% endblock %}
        </div>
    </body>
</html>

HTML Code for the Login Page (the file is named login.html):

{% extends "base.html" %}
{% block main %}
    <div id = "login">
        <form class = "form-horizontal" name = "LoginForm" action = "/login/" method = "post">
        {% csrf_token %}
        {% if next %}
            <input type = "hidden" name = "next" value = "{{ next }}" />
        {% endif %}
        <div class = "control-group">
            <label class = "control-label" for = "username">Username</label>
            <div class = "controls">
                <input type = "text" id = "username" placeholder = "Username">
            </div>
        </div>
        <div class = "control-group">
            <label class = "control-label" for = "password">Password</label>
            <div class = "controls">
                <input type = "password" name = "password" id = "password" placeholder = "Password">
            </div>
        </div>
        <div class = "control-group">
            <div class = "controls">
                <button type = "submit" class = "btn">Login</button>
            </div>
        </div>
        </form>
    </div>
{% endblock %}

解决方案

I had the same error, and i did this and it worked. Change:

username = request.POST['username']
password = request.POST['password'] 

to:

username = request.POST.get('username')
password = request.POST.get('password')

The above handles both the POST and GET methods that may result. I hope this helped.

这篇关于在登录页面POST请求后Django中生成MultiValueDictKeyError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆