MultiValueDictKeyError / request.POST [英] MultiValueDictKeyError / request.POST

查看:87
本文介绍了MultiValueDictKeyError / request.POST的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为我在 request.POST ['title']


MultiValueDictKeyError在/博客/添加/帖子/
标题
请求方法:GET
请求网址: http://119.81.247.69:8000/blog/add/post/
Django版本:1.8.2
异常类型:MultiValueDictKeyError
异常值:

'title'
异常位置: getitem <中的/usr/local/lib/python2.7/dist-packages/django/utils/datastructures.py / strong>,第322行
Python可执行文件:/ usr / bin / python
Python版本:2.7.3

MultiValueDictKeyError at /blog/add/post/ "'title'" Request Method: GET Request URL: http://119.81.247.69:8000/blog/add/post/ Django Version: 1.8.2 Exception Type: MultiValueDictKeyError Exception Value:
"'title'" Exception Location: /usr/local/lib/python2.7/dist- packages/django/utils/datastructures.py in getitem, line 322 Python Executable: /usr/bin/python Python Version: 2.7.3

views.py

def add_post(request):
    entry_title = request.POST["title"]
    return HttpResponse('Hello %s' % entry_title)

write.html

<form method="POST" action="/blog/add/post/">
<p>
    <label for "title">Title</label>
    <input type="text" id="title" name="title" value="" />
</p>
<p>
    <label for 'category'>Category</label>
    <select id="category" name="category"></select>
</p>
<p>
    <label for 'tags'>Tags</label>
    <input type="text" id="tags" value="" />
</p>
<p>
    <textarea id="content" name="content"></textarea>
</p>
<p>
    <input type="submit" value="Write" />
</p>

推荐答案

更改:

def add_post(request):
    entry_title = request.POST["title"]
    return HttpResponse('Hello %s' % entry_title)

至:

def add_post(request):
    entry_title = request.POST.get("title", "Guest (or whatever)")
    return HttpResponse('Hello %s' % entry_title)

并且不会抛出 KeyError ,但是您应该考虑使用Django的表单,而不是直接从POST数据中提取值。

and it won't throw a KeyError, but you should look at using Django's forms rather than pulling values directly from the POST data.

,您可以保留现有代码,只需检查异常即可:

Alternatively, you can keep your existing code and simply check for the exception:

def add_post(request):
    try:
        entry_title = request.POST["title"]
    except KeyError:
        entry_title = "Guest"
    return HttpResponse('Hello %s' % entry_title)

但是这就是 .get()在内部已经完成的工作。

but this is what .get() does internally already.

这篇关于MultiValueDictKeyError / request.POST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆