Django views.py在基于类的视图中更新类别选择中的分页

时间:2016-02-11 18:37:59

标签: python django django-views

问题有点复杂。 事实上,我并没有试图重新发明轮子,因为后端开发者离开了,我正尽力不要破坏他的代码。

但是,我想这次我需要改变很多东西。或许答案很简单,我的经验之湖与我对抗。

基本上,我有一个文章列表,您可以按类别排序。

我在网址中对这些进行了分类:

urlpatterns = patterns(
  '',
  url(r'^$', ArticleListView.as_view(), name='articles-list'),
  url(r'^source/(?P<source>[\w\.@+-]+)/$', SourceEntriesView.as_view(), name='articles-source'),
  url(r'^date/(?P<daterealization>[\w\.@+-]+)/$', DateEntriesView.as_view(), name='articles-date'),
  url(r'^country/(?P<region>[\w\.@+-]+)/$', RegionEntriesView.as_view(), name='articles-region'),
  url(r'^global/$', GlobalEntriesView.as_view(), name='articles-global'),
)

,主网址为mydomain.com/en/press/

所以基本上,当我尝试按来源对文章进行排序时,例如,我有这个类别的文章显示。但是分页仍然包含所有文章。

所以,如果该类别中只有一篇文章,那么这篇文章只会显示,但是我的&#34; loadMore按钮&#34;没有被禁用,因为它考虑到有更多的文章背后。

这是主要的views.py基类视图,首先是基数:

class BaseArticleListView(ListView):
"""
Base article list view for manage ajax navigation
"""
model = Article
context_object_name = 'article_list'
template_name = 'base_templates/template_press.html'
paginate_by = get_setting('PAGINATION')

def get_load_more_url(self, request, context):
    args = request.GET.copy()
    page_obj = context.get('page_obj', None)

    if not page_obj or not page_obj.has_next():
        return ''

    args[self.page_kwarg] = page_obj.next_page_number()

    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)

通用列表条目视图:

#Main article display view 
class ArticleListView(FormMixin, BaseArticleView, BaseArticleListView, ContextSourcesMixin):
  model = Article
  view_url_name = 'djangocms_press:articles-list'
  form_class = SourcesRegionsFilterForm

  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[self.context_object_name] = context['object_list']

    source_qs = ArticleSource.objects.active_translations(get_language()).order_by('translations__name')
    date_realization_for_articles = Article.objects.values_list('date_realization',
                                                        flat=True).distinct()
    region_for_articles = Country.objects.exclude(regions_press_article=None).order_by('name')

    context['load_more_url'] = self.get_load_more_url(request, context)
    context['dates_realization'] = date_realization_for_articles.dates('date_realization', 'month', order="DESC")
    context['sources_list'] = source_qs
    context['regions_list'] = region_for_articles

    return self.render_to_response(context)

  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

您可以看到此行更新了loadmore按钮:

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

end FINALLY管理已排序源的类:

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

  def get(self, *args, **kwargs):
    # submit object to cms toolbar to get correct language switcher behavior
    if hasattr(self.request, 'toolbar'):
        self.request.toolbar.set_object(self.source)
    return super(SourceEntriesView, self).get(*args, **kwargs)

  @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
    context = super(SourceEntriesView, self).get_context_data(**kwargs)
    return context

因此,当您选择一个源时,最后一个类是从URL调用ajax。但是如何从这里更新加载更多按钮?我迷路了。

在阅读有关分页和基类视图的文档后,我的结论是删除这些行。但我害怕打破一切,而且我无法使其正常运作。

所以,我的问题是更新分页的最佳方式是什么?按某些类别对象进行排序?

提前感谢您,至少在我的请求上花费的时间。

1 个答案:

答案 0 :(得分:3)

所以,因为它很复杂(但最终没有)我重写了一切。

现在它正在工作,回到过去的美好时光(再次擦除/编码)。

感谢所有花时间阅读我的请求的人,即使不幸的是没有人能给出答案!