django搜索表单错误

时间:2016-02-28 11:35:06

标签: python django search-form

这些views.py和search_form.html效果很好。 当我提交带有空白输入或长字符的表单时,错误将显示给我。

views.py:#works correct

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:#works correct

<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>

但是当我将这2个文件更改为以下文件时,提交空白表单后没有任何反应。没有提出任何错误。

views.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>

有什么问题?

0 个答案:

没有答案