简单的表格处理djangobook,版本2

时间:2014-03-19 12:54:58

标签: html django forms

我正在撰写一个简单的搜索视图。我的views.py代码是

def search(request):
     error = False
     if 'q' in request.GET:
          q = request.GET['q']
          if not q:
             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_results.html是

<p>You searched for: <strong>{{ query }}</strong></p>

{% if books %}
    <p>Found {{ books|length }} book{{ books|pluralize }}.</p>
    <ul>
        {% for book in books %}
        <li>{{ book.title }}</li>
        {% endfor %}
    </ul>
{% else %}
    <p>No books matched your search criteria.</p>
{% endif %}

我的search_form.html是

<html>
<head>
    <title>Search</title>
</head>
<body>
{% if error %}
       <p style="color: red;">Please submit a search term.</p>
    {% endif %}
    <form action="" method="get">
    <input type="text" name="q">
    <input type="submit" value="Search">
    </form>
</body>
</html>

问题是它没有开启错误=真实条件。假设在出现错误时转到search_form.html,并且应该重新加载带有红色错误消息的搜索表单。但在两种情况下都转到了search_result.html。 任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

django doc非常好地解释了如何使用表单。我想你应该阅读:https://docs.djangoproject.com/en/1.6/topics/forms/