python - 在 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>
提前致谢 !
解决方案
您不会从search
视图中返回结果。您传递的上下文仅包含查询。
此外,home.html
您没有迭代结果,试图显示它们。
推荐阅读
- vba - 在 LibreOffice Calc 中自动化图表的标题
- python - 数据科学名称错误:在 spyder 中使用 python
- spring - R2DBC 无法读取 oracle 数据库的 URL
- java - 对对象的公共引用
- security - 如何为单个用户实现多个身份验证提供程序
- python - Python - [Errno 13] 权限被拒绝。无法打开文件
- vue.js - vue 引导表的自定义模板
- c# - ASP.NET C# WebAPI 中的 IronWebScraper 不调用 Parse
- javascript - JavaScript 在 defineProperty 中使用原始的 getter/setter
- python - Python异步进程以不同的顺序执行