这些views.py 和search_form.html 运行良好。当我提交带有空白输入或长字符的表单时,将向我显示错误。
views.py: #工作正常
def search(request):
error = False
if 'q' in request.GET:
q = request.GET['q']
if not q:
error = True
elif len(q) > 20:
error = True
else:
books = Book.objects.filter(title__icontains=q)
return render(request, 'search_results.html',
{'books': books, 'query': q})
return render(request, 'search_form.html',
{'error': error})
search_form.html:#工作正常
<html>
<head>
<title>Search</title>
</head>
<body>
{% if error %}
<p style="color:red;">Please submit a search term 20 characters or shorter</p>
{% endif %}
<form action="/search/" method="get">
<input type="text" name="q">
<input type="submit" value="Search">
</form>
</body>
</html>
但是当我将这两个文件更改为下面的那些文件时,提交空白表单后没有任何反应。没有引发错误。
视图.py:
def search(request):
errors = []
if 'q' in request.GET:
q = request.GET['q']
if not q:
errors.append('Enter a search term.')
elif len(q) > 20:
errors.append('Please enter at most 20 characters.')
else:
books = Book.objects.filter(title__icontains=q)
return render(request, 'search_results.html',
{'books': books, 'query': q})
return render(request, 'search_form.html',
{'errors': errors})
search_form.html:
<html>
<head>
<title>Search</title>
</head>
<body>
{% if errors %}
<ul>
{% for error in errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
<form action="/search/" method="get">
<input type="text" name="q">
<input type="submit" value="Search">
</form>
</body>
</html>
问题是什么?