模板标记{%if%} {%endif%}无效。我需要在搜索查询后才显示页面上的搜索结果。但由于某种原因,当页面加载时,所有现有内容立即出现。但是在get请求过滤器正常工作之后。
views.py
def search(request):
place_list = Places.objects.all()
place_filter = PlaceFilter(request.GET, queryset=place_list)
return render(request, 'search/user_list.html', {'filter': place_filter})
HTML
{% if filter.qs %}
<div class="row">
{% for obj in filter.qs %}
<div class="col-md-3 admin__block">
<div class="cover__wrapper">
<img src="{{ obj.main_photo.url }}" alt="">
<a href="#"><span>#</span>{{ obj.name }}</a>
<p>{{ obj.description }}</p>
</div>
</div>
{% endfor %}
</div>
{% endif %}
filters.py
class PlaceFilter(django_filters.FilterSet):
name = django_filters.CharFilter(lookup_expr='icontains', widget=forms.TextInput(attrs={
'placeholder': 'Search place', 'class': 'input__search'}))
class Meta:
model = Places
fields = ['name']
答案 0 :(得分:2)
FilterSet
&#39; qs
属性返回filterset&#39; s queryset
。所以它总是True
。
您可以在模板中使用request.GET
来检查GET
是否包含任何请求数据,并仅渲染过滤后的数据:
{% if request.GET %}
<div class="row">
{% for obj in filter.qs %}
<div class="col-md-3 admin__block">
<div class="cover__wrapper">
<img src="{{ obj.main_photo.url }}" alt="">
<a href="#"><span>#</span>{{ obj.name }}</a>
<p>{{ obj.description }}</p>
</div>
</div>
{% endfor %}
</div>
{% endif %}