我创建了一个简单的django博客,我想在其中提供搜索选项。所以,我尝试了并且没有得到任何错误。
但是问题是我什至没有得到任何搜索结果。即使有与该查询相关的帖子,其也会显示空白页面。帮帮我。
我的代码在这里......
views.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})
urls.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"),
]
models.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
home.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>
提前谢谢!
答案 0 :(得分:1)
您不会从search
视图返回结果。您传递的上下文仅包含查询。
此外,在home.html
中,您没有遍历结果以尝试显示它们。