【问题标题】:why my search bar is not working in Django?为什么我的搜索栏在 Django 中不起作用?
【发布时间】:2020-11-25 09:16:23
【问题描述】:

在 Django 博客中创建了一个简单的搜索,但它不起作用。为什么搜索栏在博客网络应用程序中不起作用?在搜索框中搜索内容时,在搜索栏中没有任何内容可搜索。

- urls.py

urlpatterns = [
    path('', views.home, name='home'),
    path('about', views.about, name='about'),
    path('contact', views.contact, name='contact'),
    path('search', views.search, name='search'),
]

-views.py

def search(request):
query = request.GET['query']
allPosts = Post.objects.filter(title__icontains=query)
params = {'allPosts': allPosts}
return render(request,'home/search.html', params)

- search.html

{% extends 'base.html' %}

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

{% block blogactive %}active{% endblock blogactive %}

{% block body %}
<div class="container my-3">
            <h2>Search Results</h2>
            {% for post in allposts %}
            <div class="row no-gutters border rounded overflow-hidden flex-md-row my-4 shadow-sm h-md-250 position-relative">
                <div class="col p-4 d-flex flex-column position-static">
                    <strong class="d-inline-block mb-2 text-primary">Article by {{post.author}}</strong>
                    <h3 class="mb-0">{{post.title}}</h3>
                    <div class="mb-1 text-muted">{{post.datetime}}</div>
                    <p class="card-text mb-auto">{{post.content | truncatechars:500}}</p>
                    <div class='my-2'>
                    <a href="/blog/{{post.slug}}" role='button' class="btn btn-primary">Continue reading</a>
                    
                </div>
                <div class="col-auto d-none d-lg-block">

                </div>
            </div>

            
        </div>
        {% endfor %}
{% endblock body %}

【问题讨论】:

    标签: django django-views django-templates django-urls


    【解决方案1】:

    您的代码中有错字。在模板中,您使用allposts(全部小写),您从上下文中传递allPosts,即:params = {'allPosts': allPosts}。所以你需要改变其中任何一个,比如改变上下文:

    params = {'allposts': allPosts}
    

    还有一个改进建议,将模板中的href="/blog/{{post.slug}}" 替换为href="{% url 'url_name' %}"。更多信息可以在url tag documentation找到。

    【讨论】:

    • 谢谢,现在它正在工作,我将替换模板中的 href。
    • 太棒了。那么请考虑标记this answer as accepted。谢谢
    猜你喜欢
    • 1970-01-01
    • 2021-07-19
    • 2021-10-22
    • 2016-10-16
    • 2019-12-17
    • 2021-12-09
    • 1970-01-01
    • 2021-10-04
    • 2015-04-06
    相关资源
    最近更新 更多