gpt4 book ai didi

python - MultiValueDictKeyError/request.POST

转载 作者:太空狗 更新时间:2023-10-30 01:54:08 27 4
gpt4 key购买 nike

我想我在 request.POST['title'] 有问题

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 数据中提取值。

或者,您可以保留现有代码并简单地检查异常:

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

但这是 .get() 内部已经做的事情。

关于python - MultiValueDictKeyError/request.POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30696030/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com