我在文档中找不到它,所以我在这里问。我已经使用 django-filter 创建了过滤器,它可以正常工作,但是如果有人选择没有对象的过滤器,则用户将获得空白页。我想添加简单的段落
没有条件匹配
如果过滤的对象不存在。
我尝试过使用类似模板标签的
{%,如果obj在filter.qs中!=无%} {%endif%}
但是它不起作用。有人知道怎么做吗?
filters.py
import django_filters
from .models import Company, COMPANY_TECHNOLOGIES
from django_filters import ChoiceFilter
class CompanyFilter(django_filters.FilterSet):
class Meta:
model = Company
fields = ['type', 'city', 'students']
def __init__(self, *args, **kwargs):
super(CompanyFilter, self).__init__(*args, **kwargs)
self.filters['type'].extra.update(
{'empty_label': 'All'})
self.filters['city'].extra.update(
{'empty_label': 'All'})
self.filters['students'].extra.update(
{'empty_label': 'All'})
comp_list.html
{% extends 'company/base.html' %}
{% block content %}
<div id="filter">
<form action="" method="get" id="submit">
{{ filter.form.as_p }}
<input type="submit"/>
</form>
{% for obj in filter.qs %}
<a href="/brands/{{obj.id}}">{{ obj.name }}</a>
<p>Image {% if obj.image != None %}
<img src="{{ obj.image.url }}">
{% endif%}</p>
<p>Icon {% if obj.icon != None %}
<img src="{{ obj.icon.url }}" width="30" height="30">
{% endif%}</p>
<br> Type: {{ obj.type }} City: {{ obj.city }} Stack: {{ obj.stack }}
{% if obj not in filter.qs %}
<p>no matches</p>
{% endif %}
{% endfor %}
{% endblock %}
</div>
views.py
from django.shortcuts import render, get_object_or_404, redirect
from django.utils import timezone
from .models import Company
from .filters import CompanyFilter
from rest_framework import viewsets
from .serializers import CompanySerializer
# Create your views here.
def comp_list(request):
f = CompanyFilter(request.GET, queryset=Company.objects.all())
return render(request, 'company/comp_list.html', {'filter': f})
##def brands(request, slug):
##brands = Company.objects.all()
##return render(request, 'company/comp_view.html', {'brands': brands})
def brands(request, pk):
brand = get_object_or_404(Company, pk=pk)
return render(request, 'company/comp_view.html', {'brand': brand})
#rest api
class CompanyViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows groups to be viewed or edited.
"""
queryset = Company.objects.all()
serializer_class = CompanySerializer
答案 0 :(得分:0)
抱歉,请您花一些时间,我应该直接去Django文档,并使用内置的模板标记
{% empty %}
我刚刚将其添加到我的comp_list.html中,如下所示
{% extends 'company/base.html' %}
{% block content %}
<div id="filter">
<form action="" method="get" id="submit">
{{ filter.form.as_p }}
<input type="submit"/>
</form>
{% for obj in filter.qs %}
{% if obj in filter.qs %}
<a href="/brands/{{obj.id}}">{{ obj.name }}</a>
<p>Image {% if obj.image != None %}
<img src="{{ obj.image.url }}">
{% endif%}</p>
<p>Icon {% if obj.icon != None %}
<img src="{{ obj.icon.url }}" width="30" height="30">
{% endif%}</p>
<br> Type: {{ obj.type }} City: {{ obj.city }} Stack: {{ obj.stack }}
{% endif %}
{% empty %}
<p>no matches</p>
{% endfor %}
{% endblock %}</div>
现在一切正常,如果用户尝试使用不匹配的条件过滤对象,他将在<p> No Matches </p>
段得到响应