【问题标题】:Website in Django Python. My search results are not showing in the webpageDjango Python 中的网站。我的搜索结果未显示在网页中
【发布时间】:2021-09-04 23:59:48
【问题描述】:

这是我的views.py搜索:

def search_results(request):
if request.method == "POST":
    query = request.POST['query']
    allPosts = Post.objects.filter(name__contains=query)
    return render(request, 'search.html', {'query': query, 'allPosts':allPosts})

else:
    return render(request, 'search.html')

这是我的 search.html:

{% extends 'base.html' %}

{% block title %}Search Results{% endblock title %}

{% block content %}

{% if query %}
<h1>
  You Searched For {{query}}
</h1>
{% else %}
<h1>
  You Forgot to Search!.....
</h1>
{% endif %}

{% endblock content %}

这是表单代码:

<form method="GET" action="/search_results" class="my-2 my-lg-0 mx-3">
        
        <input class="mr-sm-2" type="search" placeholder="Search" aria-label="Search" id="query" name="query">
        <button class="btn btn-outline-light my-2 my-sm-0" type="submit">Search</button>
      </form>

现在,我的注销按钮遇到了同样的问题。它将我重定向到 post.html 页面。我不知道这个问题究竟来自哪里。 当我重新加载搜索页面时,它不会显示任何搜索结果。

【问题讨论】:

    标签: python html search


    【解决方案1】:

    表单应该根据您的观点发送 POST 而不是 GET:

     <form method="POST" action="/search_results" class="my-2 my-lg-0 mx-3">  
         <input class="mr-sm-2" type="search" placeholder="Search" aria-label="Search" id="query" name="query">
         <button class="btn btn-outline-light my-2 my-sm-0" type="submit">Search</button>
     </form>
    

    然后在你的 html 上显示结果:

    {% extends 'base.html' %}
    {% block title %}Search Results{% endblock title %}
    
    {% block content %}
    
    {% if query %}
    <h1>
        You Searched For {{query}}
    </h1>
    <ul>
    {% for post in allPosts %}
        <li>{‌{ post }}</li>
    {% endfor %}
    </ul>
    {% else %}
    <h1>
        You Forgot to Search!.....
    </h1>
    {% endif %}
    

    当然帖子必须根据您的目的进行解析

    【讨论】:

    • “它不起作用”不是一个有用的响应。错误?什么?
    • 同样的问题。结果没有显示。而且服务器也没有抛出任何错误。
    • 每当我重新加载页面以进行任何搜索时,它都会将我带到 post.html 页面。我认为这就是为什么没有显示任何结果的原因。但我不知道为什么会这样。我的 search.html 端点不工作。有人帮我解决这个问题吗?
    最近更新 更多