首页 > 解决方案 > 在 django 搜索中没有得到结果

问题描述

我创建了一个简单的 django 博客,我想在其中提供搜索选项。所以,我试过了,甚至没有得到任何错误。

但问题是我什至没有得到任何搜索结果。即使有与该查询相关的帖子,它也会显示空白页面。帮帮我,伙计们。

我的代码在这里......

视图.py

class home_view(ListView):
    model = home_blog_model
    template_name = "home.html"
    context_object_name = "posts"
    paginate_by = 8
    ordering = ['-date']


def search(request):
    query = request.GET.get("key")

    if query:
        results = home_blog_model.objects.filter(Q(title__icontains=query))
    else:
        results = home_blog_model.objects.filter(status="Published")


    return render(request , "home.html" , {"query":query})

网址.py

from django.urls import path
from . import views
from django.contrib.auth.views import LoginView , LogoutView
urlpatterns = [

    path("" , views.home_view.as_view() , name="blog-home"),
    path("posts/<int:pk>/" , views.detail_view , name="detail"),
    path("admin/login/" , LoginView.as_view(template_name="admin-login.html") , name="admin-login"),
    path("admin/logout/" , LogoutView.as_view() , name="admin-logout"),
    path("admin/post/create/" , views.create_post_view , name="create_post"),
    path("post/search/" , views.search , name="search_post"),
]

模型.py

from django.db import models

class home_blog_model(models.Model):
    title = models.CharField(max_length=100)
    summary = models.CharField(max_length=300)
    content = models.TextField()
    date = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.title

主页.html

<div align="right">
    <form class="form-group" method="GET" action="{% url 'search_post' %}">
        <input type="text" name="key" placeholder="search........" value="{{request.GET.key}}">
        <button class="btn" type="submit">Search</button>
    </form>
</div>

提前致谢 !

标签: pythondjangosearchpagination

解决方案


您不会从search视图中返回结果。您传递的上下文仅包含查询。

此外,home.html您没有迭代结果,试图显示它们。


推荐阅读