2013-08-06 145 views
-1

所以我有一個視圖稱爲索引,可能會或可能不會收到POST表單。我在這裏看到類似這樣的問題,並注意到大多數情況下,它似乎是視圖中的一個簡單的邏輯錯誤,但是我寫入視圖的方式是,渲染調用超出所有條件,它應該始終被調用。觀點是這樣的:查看不返回HttpResponse對象

from django.shortcuts import render, render_to_response, redirect 
from django.template import RequestContext 
from django.http import HttpResponse, Http404 

import datetime 

myUsers = ['A', 'B', 'C', 'D', 'E', 'Guest'] 

def index(request): 
    # grab user if we've submitted login form from this page 
    if request.method == 'POST': 
     if 'myUser' in request.POST: 
      request.session['myUser'] = request.POST['myUser'] 
    # make login default guest if not logged in 
    elif not 'myUser' in request.session: 
     request.session['myUser'] = 'Guest' 

    return render(request, 'home/index.html', {'myUsers': myUsers}) 

我相當堅持的解決方案,並將不勝感激!

編輯:這也是回溯。

Environment: 


Request Method: GET 
Request URL: http://transcode50.com/home/ 

Django Version: 1.5.1 
Python Version: 2.7.3 
Installed Applications: 
('django.contrib.auth', 
'django.contrib.contenttypes', 
'django.contrib.sessions', 
'django.contrib.sites', 
'django.contrib.messages', 
'django.contrib.staticfiles', 
'django.contrib.admin', 
'bootstrap_toolkit', 
'transcode', 
'transcode50', 
'home', 
'books') 
Installed Middleware: 
('django.middleware.common.CommonMiddleware', 
'django.contrib.sessions.middleware.SessionMiddleware', 
'django.middleware.csrf.CsrfViewMiddleware', 
'django.contrib.auth.middleware.AuthenticationMiddleware', 
'django.contrib.messages.middleware.MessageMiddleware') 


Traceback: 
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response 
    133.      raise ValueError("The view %s.%s didn't return an HttpResponse object." % (callback.__module__, view_name)) 

Exception Type: ValueError at /home/ 
Exception Value: The view home.views.index didn't return an HttpResponse object. 
+0

你能否顯示錯誤的追溯? –

+0

當然可以;發佈。 – coltonoscopy

+1

基於該代碼,我不知道這也可能發生。任何機會,這是一個縮進問題?在這裏複製的代碼中可能不會很好地顯示。 –

回答

-1

我想你應該調整是這樣的:

if request.method == 'POST': 
    for user in myUsers: 
     if user in request.POST: 
      request.session['myUser'] = request.POST['myUser'] 

request.POST是類字典對象,你的myUsers是一個列表。我不認爲你可以在request.POST直接在Python中做myUser。它是我的2美分。

+0

https://docs.djangoproject.com/en/dev/ref/request-response/#id3 - 「QueryDict實現了所有的標準字典方法,因爲它是字典的一個子類。」示例視圖以有效的方式測試POST querydict中「myUser」鍵的存在。 –

0

彼得的答案是,縮進是關閉的。它在我的文本編輯器中完美排列,但是將所有行切換並重新標記以解決問題。謝謝!

相關問題