如何为 django 的所有模板添加搜索栏功能?



我正在尝试在我的django网站中添加一个搜索栏。我在基本模板中添加了一个表单。我已将该功能添加到我的主视图中。它在主视图中工作。但不是其他观点。我尝试创建一个新视图,但即也不起作用。请告诉我我该怎么办?

views.py:

def search(request):
if request.method == "GET":
query = request.GET.get('q').split()
if query:
queryset =  reduce(
operator.__or__,
[
Q(title__icontains=queries) | Q(content__icontains=queries)
for queries in query
]
)
posts = Post.objects.filter(queryset).distinct()
return render(request, "blog/home.html", {'posts': posts})

模板:-

<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" action="{% url 'blog-home' %}" method="GET" type="search" placeholder="Search Posts" aria-label="Search" name="q">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>

urls.py

urlpatterns = [
path('', PostListView.as_view(), name='blog-home'),
path('user/<str:username>', UserPostListView.as_view(), name='user-posts'),
path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
path('post/new/', PostCreateView.as_view(), name='post-create'),
path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'),
path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'),
path('about/', views.about, name='blog-about'),
path('comment/<int:pk>/approve/', views.comment_approve, name='comment_approve'),
path('comment/<int:pk>/remove/', views.comment_remove, name='comment_remove'),
path('comment/<int:pk>/delete/', views.comment_delete, name='comment_delete'),
path('summernote/', include('django_summernote.urls')),
path('feedback/', views.contact_us, name='contact_us'),
path('search/', views.search),
]

这就是我执行搜索功能的方式。首先,我们获取所需模型的对象,然后获取q,这是我模板中输入的名称,然后根据所需的字段进行过滤。我之前提到的表单操作是您的问题的解决方案。

view.py

def course_view(request):
latest_course = Course.objects.all()
query = request.GET.get('q')
print(query)
if query:
latest_course = Course.objects.filter(
Q(title__icontains=query)|
Q(user__full_name=query)|
Q(price__icontains=query)
)
context = {
'latest_course': latest_course,
}
return render(request, 'apps/course.html', context)

模板.html(它在我的基本模板中,就像你的一样(

<div class="sidebar-search">
<form method="GET" action="{% url 'courses' %}">
<div class="input-group">
<input type="text" class="form-control search-menu" placeholder="Search..." name='q'>
<div class="input-group-append">
<span class="input-group-text">
<i class="fa fa-search" aria-hidden="true"></i>
</span>
</div>
</div>
</form>
</div>

在模板表单标记中添加要加载搜索函数的 URL 名称。通过这种方式,您可以从任何页面进行搜索,并将您重定向到该页面。如果你不明白,我可以给你一个参考代码,以便你掌握一些想法。

<form method="GET" action="{% url 'courses' %}">

最新更新