1

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'),

)

ビュー.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 %}
4

2 に答える 2

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()
于 2014-10-26T02:23:22.267 に答える
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() を削除しました

于 2013-04-16T16:30:46.783 に答える