【问题标题】:Why is this Django class-based year archive view not working?为什么这个基于 Django 类的年份存档视图不起作用?
【发布时间】:2013-04-09 02:15:12
【问题描述】:

我正在尝试对 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 %}

【问题讨论】:

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


    【解决方案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')
    

    我添加了一个查询集属性并删除了 get_context_data()

    【讨论】:

    • 不知道为什么我让它变得如此复杂。有效。谢谢!
    【解决方案2】:

    我遇到了同样的问题。除了YearArchiveView,所有ArchiveViews 都在工作。在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()
    

    【讨论】:

      猜你喜欢
      • 2020-12-25
      • 2013-04-06
      • 1970-01-01
      • 1970-01-01
      • 2019-09-24
      • 2011-12-20
      • 2021-10-10
      • 2023-03-20
      • 1970-01-01
      相关资源
      最近更新 更多