Jay Cee
Jay Cee

Reputation: 1965

Django pagination return all elements but still paginate

I am trying to do something supposed to be simple and easy with django :

have a pagination of a list of items.

So, I have an article page, I want to display a maximum of 10 articles per page, next page = 10 next articles etc.

You can order them by some categories as sources or dates.

So, when I arrive on my mydomaine.com/articles/ I have all my elements displayed.

If I sort by sources, as this views.py show :

class SourceEntriesView(ContextSourcesMixin, BaseArticleView, BaseArticleListView):
model = Article
context_object_name = 'article_list'
template_name = 'base_templates/template_press.html'
_source = None
paginate_by = get_setting('PAGINATION')
view_url_name = 'djangocms_press:articles-source'

@property
def source(self):
    if not self._source:
        try:
            source_qs = ArticleSource.objects.active_translations(
                get_language(),
                slug=self.kwargs['source']
            )

            #source_qs = source_qs.filter(site=Site.objects.get_current().pk)
            self._source = source_qs.latest('pk')
        except ArticleSource.DoesNotExist:
            raise Http404("ArticleSource does not exist for this site")
    return self._source

def get_queryset(self):
    qs = super(SourceEntriesView, self).get_queryset()
    if 'source' in self.kwargs:
        qs = qs.filter(sources__pk=self.source.pk)
    return qs

def get_context_data(self, **kwargs):
    kwargs['source'] = self.source
    return super(SourceEntriesView, self).get_context_data(**kwargs)

Once the ajax call is made to load this view and display the articles sorted by source, I have my 10 items ! (well, I am trying with 4 while testing).

So why isn't it working on the main page.

Here are more explanations with my code :

''' Main article display view '''
class ArticleListView(FormMixin, BaseArticleListView, ContextSourcesMixin):
  model = Article
  context_object_name = 'article_list'
  template_name = 'base_templates/template_press.html'
  view_url_name = 'djangocms_press:articles-list'
  form_class = SourcesRegionsFilterForm
  paginate_by = get_setting('PAGINATION')


def get_form_kwargs(self):
    return {
        'initial': self.get_initial(),
        'prefix': self.get_prefix(),
        'data': self.request.GET or None,
        'request': self.request,
    }

def get(self, request, *args, **kwargs):
    """
    Handle the form submissions to filter by Sources and regions
    First_object is use for pagination
    """
    context = {}

    self.object_list = self.get_queryset().order_by("-date_realization")

    first_object = 0

    if 'article' in self.request.GET:
        try:
            project_id = int(request.GET['article'])
            context['article_render'] = self.object_list.get(pk=project_id)
        except (Article.DoesNotExist, ValueError):
            pass

    form = self.get_form(self.form_class)

    if form.is_valid():
        if form.cleaned_data['regions']:
            self.object_list = self.object_list.filter(
                Q(regions__continent=form.cleaned_data['regions']) | Q(global_regions=True)).distinct()

    context.update(self.get_context_data(form=form))

    context['load_more_url'] = self.get_load_more_url(request, context)

    context[self.context_object_name] = self.object_list
    context['object_list'] = self.object_list
    source_qs = ArticleSource.objects.active_translations(get_language())
    context['sources_list'] = source_qs
    date_realization_for_articles = Article.objects.values_list('date_realization',
                                                        flat=True).distinct()
    context['dates_realization'] = date_realization_for_articles.dates('date_realization', 'month', order="DESC")

    return self.render_to_response(context)

def get_load_more_url(self, request, context):
    args = request.GET.copy()
    return '?{}'.format(args.urlencode())

def render_to_json_response(self, context, **response_kwargs):
    if 'current_app' not in context:
        context['current_app'] = resolve(self.request.path).namespace

    c = RequestContext(self.request, context)

    html_items_list = render_to_string(
        'base_templates/template_press.html',
        context,
        context_instance=c)

    html_items_list = html_items_list.strip()

    json_response = {
        'html_items_list': html_items_list,
        'load_more_url': self.get_load_more_url(self.request, context),
    }

    return JsonResponse(json_response)

def render_to_response(self, context):
    if self.request.is_ajax():
        response = self.render_to_json_response(context)
    else:
        response = super(ArticleListView, self).render_to_response(context)
    return response

This was the main view that displays articles.

my settings, very simple but easier to use :

def get_setting(name):
  from django.conf import settings
  from meta_mixin import settings as meta_settings

  default = {
    'PRESS_PAGINATION': getattr(settings, 'PRESS_PAGINATION', 4),
  }
  return default['PRESS_%s' % name]

I also tried to pass the paginated_by in the article-list url but the result is the same.

here is my part of template suppose to be paginated :

    {% if article_list %}
    <div id="articles-list" class="col-md-12">
        {% for article in article_list %}
        <div class="row article">
            <div class="col-md-2">
                {{ article.date_realization|date:"F d, Y" }}
            </div>
            <div class="col-md-2">
                {{ article.source }}
            </div>
            <div class="col-md-2">
            {% for region in article.regions.all %}
                {{ region.name }}
            {% endfor %}
            </div>
            <div class="col-md-6">
                {{ article.title }}
            </div>
        </div>
        {% endfor %}
    </div>
    {% if is_paginated %}
    <section id="content-btn">
        <div id="load-more-btn blippar-white-btn" class="col-md-2 col-md-offset-5 col-xs-8 col-xs-offset-2" align="center">
                <a id="loadmore" role="button" class="button btn load-more-btn blippar-white-btn" href="{{ load_more_url }}">{% trans 'VIEW MORE' %}</a>
        </div>
    </section>

    <div class="col-lg-12">

        <span class="current">
            Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
        </span>

        {% if page_obj.has_next %}
            <a href="?page={{ page_obj.next_page_number }}">next</a>
        {% endif %}

    </div>

    {% endif %}
{% endif %}

So, I have 2 questions :

  1. Why isn't it showing on the main articles-list ?
  2. Why, after selecting a source, if I click on "next" all my items are displayed ?

If you have an idea or an reflexion orientation, I would love it :)

Upvotes: 1

Views: 2861

Answers (2)

Mijamo
Mijamo

Reputation: 3516

I assume you are using the MultipleObjectMixin.

In this case the pagination happens when you call context.update(self.get_context_data(form=form)) . See the source there : https://github.com/django/django/blob/master/django/views/generic/list.py

So when you call this function, it sets context['object_list'] to the paginated content. Unfortunately you override it a few lines after that when you call context['object_list'] = self.object_list, because self.object_list is not impacted by the pagination. If you delete this line it should therefore be fine.

edit : As it seems you were using 'article_list' and not 'object_list', here are additional comment:

  • in your original function, at the end you had 'page' that refers to the righ pagination function, and 'article_list' and 'object_list' that refered to the full list of articles as I explained.
  • with my solution, you still had 'page' and 'article_list' unchanged, but 'object_list' was referring to the right paginated list. Unfortunately I did not notice it was not the one you were using in the template.
  • So now all you have to do is replace context[self.context_object_name] = self.object_list by context[self.context_object_name] = context['object_list'], and it will work :)

Upvotes: 2

Jay Cee
Jay Cee

Reputation: 1965

So, at the moment I have a temporary solution which is :

{% for article in page_obj.object_list %}
        <div class="row article">
            <div class="col-md-2">
                {{ article.date_realization|date:"F d, Y" }}
            </div>
            <div class="col-md-2">
                {{ article.source }}
            </div>
            <div class="col-md-2">
            {% for region in article.regions.all %}
                {{ region.name }}
            {% endfor %}
            </div>
            <div class="col-md-6">
                {{ article.title }}
            </div>
        </div>
        {% endfor %}

instead of doing :

{% for article in article_list %}
    <div class="row article">
        <div class="col-md-2">
            {{ article.date_realization|date:"F d, Y" }}
        </div>
        <div class="col-md-2">
            {{ article.source }}
        </div>
        <div class="col-md-2">
        {% for region in article.regions.all %}
            {{ region.name }}
        {% endfor %}
        </div>
        <div class="col-md-6">
            {{ article.title }}
        </div>
    </div>
    {% endfor %}

article_list became object_list. I am not very happy with it since when I read the doc this should not be necessary.

Upvotes: 0

Related Questions