Django:Django没有识别post变量

时间:2012-08-11 02:16:40

标签: python django

我很遗憾地遗漏了一些非常基本的内容,但当我尝试通过函数中的request['title']来尝试后期变量时,我收到此错误:

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/ajax/drafts/create

Django Version: 1.4
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',
 'Knights',
 'django.contrib.admin')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware')


Traceback:
File "/Library/Python/2.7/site-packages/Django-1.4-py2.7.egg/django/core/handlers/base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "/Library/Python/2.7/site-packages/Django-1.4-py2.7.egg/django/contrib/auth/decorators.py" in _wrapped_view
  20.                 return view_func(request, *args, **kwargs)
File "/Users/Mike/Desktop/Main/Django-Development/BBN/Knights/views.py" in document_create
  179.     title = request.POST['title']
File "/Library/Python/2.7/site-packages/Django-1.4-py2.7.egg/django/utils/datastructures.py" in __getitem__
  258.             raise MultiValueDictKeyError("Key %r not found in %r" % (key, self))

Exception Type: MultiValueDictKeyError at /ajax/drafts/create
Exception Value: "Key 'title' not found in <QueryDict: {}>"

该功能的完整代码是:

def document_create(request):
    user = request.user
    title = request.POST['title']
    if (title != ''):
        Draft.objects.create(content='Your content goes here', user=user, title=title)

列出的后置变量如下:

POST:
title = u'sdff'

编辑:此外,当我使用for循环列出项目时,会出现标题变量。

3 个答案:

答案 0 :(得分:3)

导致错误的请求是GET,并且您尝试从POST dict获取title参数的值。 将您的代码更改为:

def document_create(request):
    user = request.user
    title = request.GET['title']
    if (title != ''):
        Draft.objects.create(content='Your content goes here', user=user, title=title)

或者,您可以测试请求是GET还是POST,检查request.method属性。

答案 1 :(得分:1)

您确定您的请求真的是POST吗?对我来说,看起来你正试图从POST请求中检索数据,但查询实际上是一个GET请求。

此外,您应该使用if 'title' in request.POST:检查请求中是否存在变量...

此致

艾蒂安

答案 2 :(得分:1)

首先,这是一个GET查询,因此POST dict将为空。您的意思是在HTML中的表单元素中设置method='POST'吗?

其次,KeyError表示POST词典中没有关键字。你应该这样做:

title = request.POST.get('title', None)
if title is None:
    ...

如果密钥不在title中,则会将None设置为request.POST