Django request.GET [英] Django request.GET
问题描述
似乎我不能让这个例子打印你没有提交!。
每次我提交一个空的表单,它说:
It seems I cant make this example print "You submitted nothing!". Everytime I submit an empty form it says:
您提交了:u'
您没有提交任何内容
我在哪里出错?
views.py
def search(request):
if 'q' in request.GET:
message = 'You submitted: %r' % request.GET['q']
else:
message = 'You submitted nothing!'
return HttpResponse(message)
模板:
<html>
<head>
<title> Search </title>
</head>
<body>
<form action="/search/" method="get" >
<input type="text" name = "q">
<input type="submit"value="Search"/>
</form>
</body>
</html>
推荐答案
调用 / search / / code>应该导致你没有提交任何内容,但是另一方面调用
/ search /?q =
应该导致你提交了你
Calling /search/
should result in "you submitted nothing", but calling /search/?q=
on the other hand should result in "you submitted u''"
浏览器必须添加 q =
即使它是空的,因为它们必须包括所有这些部分的字段的形式。只有在Javascript中执行某些DOM操作(或自定义的JavaScript提交操作)时,您可能会遇到这样的行为,但只有当用户启用了JavaScript。所以你应该可以简单地测试非空字符串,例如:
Browsers have to add the q=
even when it's empty, because they have to include all fields which are part of the form. Only if you do some DOM manipulation in Javascript (or a custom javascript submit action), you might get such a behavior, but only if the user has javascript enabled. So you should probably simply test for non-empty strings, e.g:
if request.GET.get('q'):
message = 'You submitted: %r' % request.GET['q']
else:
message = 'You submitted nothing!'
这篇关于Django request.GET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!