0

我可能错过了一些非常基本的东西,但是当我尝试通过以下方式访问帖子变量时: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 循环列出项目时,会出现 title 变量。

4

3 回答 3

3

导致错误的请求是 GET,您正在尝试title从 POST 字典中获取参数的值。将您的代码更改为:

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属性。

于 2012-08-11T02:36:14.350 回答
1

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

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

问候

艾蒂安

于 2012-08-11T02:37:03.543 回答
1

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

其次,KeyError意味着密钥不在POST字典中。你应该这样做:

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

如果密钥不在title.Nonerequest.POST

于 2012-08-11T02:38:09.577 回答