为什么这个基于Django类的年份归档视图不起作用?

时间:2013-04-16 15:29:05

标签: django filtering django-class-based-views

我正在尝试将YearArchiveView基于类的视图子类化以显示一年中发布的文章列表,但过滤不起作用,example.com/2012显示了所有年份的文章。

请注意,我不希望想要urls.py中的视图代码。相反,我希望LogbookYearArchive包装器继续生活在views.py。

models.py:

class Entry(models.Model):

    KIND = (
        ('L', 'Link'),
        ('A', 'Article'),
    )

    title = models.CharField(max_length=200)
    slug = models.SlugField(unique_for_date='pub_date')
    kind = models.CharField(max_length=1, choices=KIND, default=1,
     help_text="Is this a link to other content or an original article?")
    url = models.URLField(blank=True, help_text="The link URL")
    body = models.TextField(blank=True)
    body_html = models.TextField()
    content_format = models.CharField(choices=CONTENT_FORMAT_CHOICES, 
                                            max_length=50, default=1)
    is_active = models.BooleanField(help_text=_("Tick to make this entry\
        live (see also the publication date). Note that administrators\
        (like yourself) are allowed to preview inactive entries whereas\
        the general public aren't."), default=True)
    pub_date = models.DateTimeField(verbose_name=_("Publication date"),
     help_text=_("For an entry to be published, it must be active and its\
      publication date must be in the past."))
    mod_date = models.DateTimeField(auto_now_add=True, editable=False)

    class Meta:
        db_table = 'blog_entries'
        verbose_name_plural = 'entries'
        ordering = ('-mod_date',)
        get_latest_by = 'pub_date'

    def __unicode__(self):
        return self.title

    @models.permalink
    def get_absolute_url(self):
        """Construct the absolute URL for an Entry of kind == Article."""
        return ('logbook-entry-detail', (), {
                            'year': self.pub_date.strftime("%Y"),
                            'month': self.pub_date.strftime("%m"),
                            'slug': self.slug})

urls.py:

from __future__ import absolute_import
from django.conf.urls import patterns, include, url

from .models import Entry
from .views import LogbookYearArchive

urlpatterns = patterns('',

    url(r'^(?P<year>\d+)/$',
        view=LogbookYearArchive.as_view(),
        name='archive-year'),

)

views.py:

from django.views.generic.list import MultipleObjectMixin
from django.views.generic import ArchiveIndexView, MonthArchiveView, YearArchiveView, DetailView
from django.core.urlresolvers import reverse

from .models import Entry

class LogbookYearArchive(YearArchiveView):
    """Yearly archives of articles"""
    model = Entry
    date_field = 'pub_date'
    year_format='%Y'
    make_object_list=True, 
    template_name = 'hth/archive_year.html'
    allow_future = False
    def get_context_data(self, **kwargs):
        context = super(LogbookYearArchive, self).get_context_data(**kwargs)
        # =todo: fix filtering by date which is not working
        context['object_list'] = Entry.objects.filter(
          is_active=True, kind='A').order_by('-pub_date', 'title')[:9999]
        return context

archive_year.html:

{% block content %}
    <h1 style="margin-bottom:1em;">Articles Published in {{ year|date:"Y" }}</h1>
    {% for object in object_list %}    
       {% ifchanged %}
           <h2 class="dateline datelinearchive">{{ object.pub_date|date:"F Y" }}</h2>
       {% endifchanged %}
           <p>
              <a href="{{ object.get_absolute_url }}">{{ object.title }}</a> 
           </p>
    {% endfor %}
{% endblock %}

2 个答案:

答案 0 :(得分:1)

你可以试试这个:

class LogbookYearArchive(YearArchiveView):
    """Yearly archives of articles"""
    model = Entry
    date_field = 'pub_date'
    year_format='%Y'
    make_object_list=True, 
    template_name = 'hth/archive_year.html'
    allow_future = False
    queryset = Entry.objects.filter(
      is_active=True, kind='A').order_by('-pub_date', 'title')

我添加了一个queryset属性并删除了get_context_data()

答案 1 :(得分:1)

我遇到了同样的问题。除ArchiveViews之外,所有YearArchiveView都在工作。在make_object_list属性中找到了解决方案。它应该是True

这是来自django代码的剪辑

if not self.get_make_object_list():
    # We need this to be a queryset since parent classes introspect it
    # to find information about the model.
    qs = qs.none()