简体   繁体   English

Django分页过滤结果CBV

[英]Django pagination filtered results CBV

How can I paginate using multiple filters in Django CBV? 如何在Django CBV中使用多个过滤器进行分页? I have some filters in my view and form and I don't know how to paginate it. 我的视图和表单中有一些过滤器,我不知道如何对其进行分页。 Everything that I've tried has failed. 我尝试过的一切都失败了。 Here my code. 在这里我的代码。

models.py models.py

class Lei(models.Model):

CHOICE_TIPO_LEI = (
    ('complementar', 'Lei complementar'),
    ('ordinaria', 'Lei ordinária'),
    ('decreto', 'Decreto'),
    ('portaria', 'Portaria'),
    ('convenio', 'Convênios Municipais'),
)

numero = models.CharField(max_length=6)
tipo_lei = models.CharField(u'Tipo do documento', max_length=15, choices=CHOICE_TIPO_LEI)
ano = models.CharField(max_length=4)
titulo = models.TextField()
arquivo = FileBrowseField("Arquivo PDF", max_length=200, extensions=[".pdf",".doc", ".xls", ".docx", ".xlsx"], directory="leis/", blank=True, null=True)
publicacao = models.DateTimeField(u'publicação', auto_now=True, blank=True)

class Meta:
    db_table = "tb_lei"
    verbose_name = "Lei"
    verbose_name_plural = "Leis"

def __str__(self):
    return self.titulo

views.py views.py

class LeisListView(ComunsNoticiasMixin, ListView):
model = Lei
template_name = 'leis/leis.html'
context_object_name = 'leis'

def get_context_data(self, **kwargs):
    context = super(LeisListView, self).get_context_data(**kwargs)
    context["an"] = Lei.objects.values('ano').distinct().order_by('-ano')
    context["tl"] = Lei.objects.values('tipo_lei').distinct().order_by('tipo_lei')
    return context
class BuscaLeiListView(ComunsNoticiasMixin, ListView):
model = Lei
template_name = 'leis/busca-leis.html'
context_object_name = 'busca_leis'
paginate_by = 1

def get_queryset(self, **kwargs):
    numero = self.request.GET.get('n')
    ano = self.request.GET.get('a')
    tipo_lei = self.request.GET.get('t')
    palavra = self.request.GET.get('p')

    leis = Lei.objects.all().order_by('-ano', '-numero')

    if numero:
        leis = leis.filter(numero=numero)
    if ano:
        leis = leis.filter(ano=ano)
    if tipo_lei:
        leis = leis.filter(tipo_lei=tipo_lei)
    if palavra:
        leis = leis.filter(titulo__icontains=palavra)
    return leis

form.html form.html

<form method="get" action="{% url 'leis:busca_lei_view' %}">
<div class="form-group">
    <select name="t" class="form-control">
        <option value="">Tipo do documento</option>
        {% for l in tl %}
            <option value="{{ l.tipo_lei }}">
                {% if l.tipo_lei   ==   "complementar" %} Leis complementares
                {% elif l.tipo_lei ==   "ordinaria" %}    Leis ordinárias
                {% elif l.tipo_lei ==   "decreto" %}      Decretos
                {% elif l.tipo_lei ==   "convenio" %}     Convênios municipais
                {% elif l.tipo_lei ==   "portaria" %}     Portarias
                {% endif %}
            </option>
        {% endfor %}
    </select>
</div>
<div class="form-group">
    <input name="n" type="text"  class="form-control"  placeholder="numero da lei, portaria ou decreto" size="10" maxlength="30">
</div>
<div class="form-group">
    <select name="a" class="form-control">
        <option value="">ano</option>
        {% for l2 in an %}
            <option value="{{ l2.ano }}">{{ l2.ano }}</option>
        {% endfor %}
    </select>
</div>
<div class="form-group">
    <button value="{{ search_term }}" class="btn btn-info">pesquisar</button>
</div>
<hr />
<div class="form-group">
    <label for="t"><strong>Ou digite um termo a ser pesquisado</strong></label>
    <input name="p" class="form-control" type="text"  placeholder="digite um termo a ser pesquisado" size="20" maxlength="30">
</div>
<button value="{{ search_term }}" class="btn btn-info">Pesquisar</button>

result.html result.html

<div class="row">
<div class="col-xs-12">
    {% if busca_leis %}
        {% for lb in busca_leis %}
            <h4 ><a href="{{ lb.arquivo.url }}" class="text-primary">
                {% if lb.tipo_lei == "complementar" %}Lei complementar n° {% elif lb.tipo_lei == "ordinaria" %} Lei ordinária nº {% elif lb.tipo_lei == "decreto" %} Decreto nº {% elif lb.tipo_lei == "convenio" %} Convênio municipal {% else %} Portaria nº{% endif %} {{ lb.numero }} de {{ lb.ano }}</a>
            </h4>
            <p class="post-content">{{ lb.titulo|safe }}</p>
            <br />
        {% endfor %}
        <br />

    {% else %}
        <br /><br />
        <div class="alert alert-warning" role="alert">
            <h5>
                O termo pesquisado não foi encontrado. Utilize os filtros para realizar a pesquisar novamente.
            </h5>
            <a href="{% url 'leis:leis_view' %}" class="btn btn-warning">voltar</a>
        </div>
    {% endif %}

</div>
{% if is_paginated %}
    <ul class="pagination">
        {% if page_obj.has_previous %}
            <li><a href="?page={{ page_obj.previous_page_number }}">&laquo;</a></li>
        {% else %}
            <li class="disabled"><span>&laquo;</span></li>
        {% endif %}
        {% for i in paginator.page_range %}
            {% if page_obj.number == i %}
                <li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li>
            {% else %}
                <li><a href="?page={{ i }}">{{ i }}</a></li>
            {% endif %}
        {% endfor %}
        {% if page_obj.has_next %}
            <li><a href="?page={{ page_obj.next_page_number }}">&raquo;</a></li>
        {% else %}
            <li class="disabled"><span>&raquo;</span></li>
        {% endif %}
    </ul>
{% endif %}

The existing querystring is being dropped when you click on the pagination, so you need to have a way to carry that information through. 当您单击分页时,现有的查询字符串将被删除,因此您需要有一种方法来传递该信息。

The best option would be to bring that information through. 最好的选择是通过这些信息。

Start by adding the "django.core.context_processors.request" to settings.py 首先将“django.core.context_processors.request”添加到settings.py

## settings.py
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.request',
)

Now, you have access to https://docs.djangoproject.com/en/1.8/ref/request-response/#querydict-objects . 现在,您可以访问https://docs.djangoproject.com/en/1.8/ref/request-response/#querydict-objects

In the template change the line: 在模板中更改行:

<a href="?page={{ page_obj.next_page_number }}">

to

<a href="?page={{ page_obj.next_page_number }}{% for key, value in request.GET.items %}{% if key != page %}&{{key}}={{value}}{% endif %}{% endfor %}"

This will loop through the keys in the querystring and ignore the pa 这将遍历查询字符串中的键并忽略pa

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM