首页 > 解决方案 > 如果搜索栏中输入的关键字在Django中不存在,如何应用if else

问题描述

我在我的博客应用程序中创建了一个搜索按钮,它返回具有相似标题的帖子。

views.py 有

def search(request):
    query = request.GET.get('query')
    posts = Post.objects.filter(title__icontains=query).order_by('-date_posted')
    params = {'posts' : posts}
    return render(request, 'blog/search.html' , params)

base.html

<form method="get" class="form-inline my-2my-lg-0 "  action="{% url 'search' %}">
                  <input class="form-control nav-item nav-link text-secondary" type="search" name="query" id="query" placeholder="Search" aria-label="Search">
                  <button class="btn btn-outline-success nav-item nav-link ml-1">Search</button>
</form>

和 search.html

{% for post in posts %} 
    <!-- starting loop (posts is keyword from view) -->
        <article class="media content-section">
            <img class="rounded-circle article-img" src="{{post.author.profile.image.url}}">
              <div class="media-body">
                <div class="article-metadata">
                  <a class="mr-2" href="{% url 'user-posts' post.author.username %}">{{ post.author }}</a>
                  <small class="text-muted">{{ post.date_posted | date:"F d, Y" }}</small>
                </div>
                <h2><a class="article-title" href="{% url 'post-detail' post.id%}">{{ post.title }}</a></h2>
                <p class="article-content">{{ post.content|slice:":200" }}</p>
                {% if post.content|length > 200 %}
                    <div class="btn-group-sm">
                        <a class="btn btn-outline-secondary" href="{% url 'post-detail' post.id%}">Read More &rarr;</a>
                    </div>
                {% endif %} 
              </div>
        </article>  
    {% endfor %} 

现在,如果用户输入与任何帖子的标题相似的关键字,则会返回这些帖子。如果没有帖子标题与该关键字匹配,则返回黑色页面。我想要一段说“没有帖子与标题匹配”而不是空白页

编辑

如何得到类似“没有帖子匹配标题{{query}}”而不是“没有帖子匹配标题”我得到

标签: django

解决方案


像这样包装你的模板:

{% if posts %}
    {% for post in posts %}
        ...
    {% endfor %}
{% else %}
    <h2> No post matches the title. </h2>
{% endif %}

由于您的帖子查询集将为空,因此它将在else块中显示该语句。


推荐阅读