2013-12-23 108 views
3

我試圖構建一個登錄頁面。我正在運行Django 1.6.1。我一直在www.fir3net.com/Django/django.html上關注該教程。爲了方便,我會在這裏重新發布很多。在登錄頁面POST請求後在Django中生成的MultiValueDictKeyError

錯誤消息:

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'" 

查看代碼(據我所知,一些進口功能,這裏所說的是多餘的我眼前的問題大多是一些從試圖按照有關如何做到這一點以前的教程冗餘代碼。 ):

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.') 

信息從urls.py文件:

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.html文件):
- 的CSS樣式是基於自舉

<!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代碼的登錄頁面(該文件名爲登錄。 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 %} 

回答

12

我有同樣的錯誤,我做到了這一點,它的工作。 變化:

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

到:

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

上述把手兩POST和GET可能導致方法。 我希望這有助於。

2

當一個請求解析爲多數民衆贊成包裹着@login_required裝飾,請求重定向到指定的URL,如果用戶沒有登錄的視圖,以便在嘗試解決您的main_page視圖,而不是記錄。 in會導致t他用戶的瀏覽器發出GET請求到/login/。然而,用於處理該網址的圖呈現POST請求:

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

通常的做法是按照一般模式用於在視圖中使用的一種形式: https://docs.djangoproject.com/en/dev/topics/forms/#using-a-form-in-a-view

具體地,檢查request.method屬性所以你可以在GET請求上正確行爲並呈現表單。或者使用built-in views,他們很容易處理。

+0

感謝您的幫助,不幸的是我無法連接到djangoproject.com域名,即使通過搜索引擎,所以我會假設該網站暫時關閉,但這對於指引我是正確的方向。我會做更多的研究並回復你。 – PyUnchained

+0

http://www.downforeveryoneorjustme.com/對於檢查那種事情很有用。 –

相關問題