gpt4 book ai didi

python - Django self.request 不通过查询进行过滤

转载 作者:行者123 更新时间:2023-12-01 01:06:04 25 4
gpt4 key购买 nike

我试图在搜索模板中实现一些基本搜索,但是当我搜索时,它在 URL 中起作用,但不会更改模板中的任何帖子。

浏览次数:

class SearchListView(ListView):
model = Post
template_name = "public/search.html"

def get_context_data(self, **kwargs):
context = super(SearchListView, self).get_context_data(**kwargs)
context['queryset'] = Post.objects.filter(live=True)
context['category'] = Category.objects.all()
return context

def SearchListView(request):
query = self.request.GET.get("q")
if query:
queryset = queryset.filter(title_icontains=query)

我不确定这是否是正确的设置方法,因为我正在观看的教程没有使用基于类的 View 。

HTML:

<div class="container mt-5 mb-5">
<div class="banner-search-main mb-5">
<form method='GET' action=''>
<p class="text-muted">Keywords:</p>
<input type="text" name='q' class="homebanner-search" placeholder="Enter your keywords" value='{{ request.get.q }}'>
<input type="submit" value="search">
</form>
</div>
<div class="detail-container">
{% for post in queryset %}
<div class="col-sm card-container">
<a href="{% url 'post-detail' post.slug %}">
<div class="main-card">
<div class="main-card-img">
<img src="https://via.placeholder.com/270x150" class="card-img-top" alt="#">
</div>
<div class="main-card-body">
<p class="featured-category category-{{ post.category.colorcode }}">{{ post.category }}</p>
<p class="featured-title">{{ post.title }}</p>
<div class="featured-authcat">
<p class="featured-author mr-3"><i class="fas fa-user mr-1"></i>{{ post.author|title }}</p>
</div>
<p class="featured-subtitle">{{ post.sub_description|truncatewords:25 }}</p>
</div>
</div>
</a>
</div>
{% endfor %}
</div>
</div>

示例: enter image description here

最佳答案

使用 get_queryset 方法的 ListView

class SearchListView(ListView):
model = Post
template_name = "public/search.html"

def get_queryset(self):
queryset = super().get_queryset().filter(live=True)
query = self.request.GET.get("q")
if query:
queryset = queryset.filter(title__icontains=query)
return queryset

def get_context_data(self, **kwargs):
context = super(SearchListView, self).get_context_data(**kwargs)
context['queryset'] = self.get_queryset()
context['category'] = Category.objects.all()
return context

关于python - Django self.request 不通过查询进行过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55345397/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com