django - 如果搜索栏中输入的关键字在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 →</a>
</div>
{% endif %}
</div>
</article>
{% endfor %}
现在,如果用户输入与任何帖子的标题相似的关键字,则会返回这些帖子。如果没有帖子标题与该关键字匹配,则返回黑色页面。我想要一段说“没有帖子与标题匹配”而不是空白页
编辑
如何得到类似“没有帖子匹配标题{{query}}”而不是“没有帖子匹配标题”我得到
解决方案
像这样包装你的模板:
{% if posts %}
{% for post in posts %}
...
{% endfor %}
{% else %}
<h2> No post matches the title. </h2>
{% endif %}
由于您的帖子查询集将为空,因此它将在else
块中显示该语句。
推荐阅读
- php - 在 wordpress 中,无法将自定义注册表单数据插入数据库,并且我的 PHP 代码正在表单上打印(我保存在简码中)
- c++ - 创建从变量读取的 FILE*
- r - 如何在R中重复序列中的每个元素不同次数
- amazon-web-services - elasticbeanstalk 部署工作环境/var/pids/web.pid 失败:没有这样的文件或目录
- javascript - 我可以仅使用帧参考模拟在 Puppeteer 中按下“Enter”键吗?
- google-sheets - Google 表格 - 使用 3 列中的数据查找最常发生的事情
- node.js - 如何使用 ExpressJS 针对 mountPath 挂载 node-oidc-provider?
- javascript - React Ace Editor 值未显示
- security - 在 Electron 桌面应用程序中存储敏感信息的最佳实践
- javascript - 在 render() 中定义渲染道具函数的性能影响?