所以我有一个名为index的视图,可能会也可能不会收到POST表单。我在这里看过这样的问题,并注意到大多数情况下它在视图中似乎是一个简单的逻辑错误,但是我写视图的方式,渲染调用是在所有条件之外,提取以便它应该永远被称为。观点是这样的:
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)
每个彼得的答案是缩进了。它完全排列在我的文本编辑器中,但是移动标记所有行并重新绑定它们解决了这个问题。谢谢!
答案 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美分。