Display date breakdown in Django

I have a pretty simple question. I want to make some general representations based on the date on the Django site, but I also want to paginate them. According to the documentation, there are page arguments and paginate_by in the object_list view, but this is not in the archive_month view. What is the “right” way to do this?

+3
source share
5 answers

Date-based generic views are not paginated. It seems you cannot add pagination by wrapping them as well, as they return the result.

. , , , .

; , . , .

+1

, , , . app/templatetags/pagify.py.

from django.template import Library, Node, Variable
from django.core.paginator import Paginator
import settings

register = Library()

class PagifyNode(Node):
    def __init__(self, items, page_size, varname):
        self.items = Variable(items)
        self.page_size = int(page_size)
        self.varname = varname

    def render(self, context):
        pages = Paginator(self.items.resolve(context), self.page_size)
        request = context['request']
        page_num = int(request.GET.get('page', 1))

        context[self.varname] = pages.page(page_num)
        return ''

@register.tag
def pagify(parser, token):
    """
    Usage:

    {% pagify items by page_size as varname %}
    """

    bits = token.contents.split()
    if len(bits) != 6:
        raise TemplateSyntaxError, 'pagify tag takes exactly 5 arguments'
    if bits[2] != 'by':
        raise TemplateSyntaxError, 'second argument to pagify tag must be "by"'
    if bits[4] != 'as':
        raise TemplateSyntaxError, 'fourth argument to pagify tag must be "as"'
    return PagifyNode(bits[1], bits[3], bits[5])

(, items):

{% load pagify %}

{% pagify items by 20 as page %}
{% for item in page %}
    {{ item }}
{% endfor %}

page_size (20) . page=5 . - , (, ), :

{{ page.paginator.num_pages }}
+3

, , , object_list , , , :

import datetime, time

def post_archive_month(request, year, month, page=0, template_name='post_archive_month.html', **kwargs):
    # Convert date to numeric format
    date = datetime.date(*time.strptime('%s-%s' % (year, month), '%Y-%b')[:3])
    return list_detail.object_list(
      request,
      queryset = Post.objects.filter(publish__year=date.year, publish__date.month).order_by('-publish',),
      paginate_by = 5,
      page = page,
      template_name = template_name,
      **kwargs)

urls.py - :

url(r'^blog/(?P<year>\d{4})/(?P<month>\w{3})/$',
    view=path.to.generic_view,
    name='archive_month'),

, .

+1

Django's generic date-based views do not support pagination. This is open ticket since 2006 . If you want, you can try the code fixes provided to implement this feature. I'm not sure why the patches have not yet been applied to the codebase.

0
source

Source: https://habr.com/ru/post/1705133/


All Articles