开发者

Replacement for num_latest with class-based date-based generic views?

I've switched to Django 1.3 in order to get pagination for my date based generic views. This works fine, however there is a page where I want a specific number of items but do not want it paginated. For example, return the first 5 news entries.

In 1.2 we had num_latest which we could put in our info dict to get the latest items. This doesn't seem to exist with the new class-based generic views.

I could set paginate_by to 5 and just not use the pagination links in the template, but then people will still be able to see the old entries by punching in the url manually (which I don't want). Furthermore I don't want Django to set up pagination that I'm not going to use.

Edit: This is the urlconf line I'm currently using:

url(r'^$', 
    ArchiveIndexView.as_view(
        model = Entry,
        context_object_name = 'entry_list',
        template_name = 'news/news.开发者_Go百科html',
        date_field = 'published',
    ), name = 'archive_index'
),

Further edit: Attempting to override get_dated_queryset I've used this bit of code in conjunction with the urlconf as above but with the new view called:

class MainIndex(ArchiveIndexView):
    def get_dated_queryset(self):
        return Entry.objects.all()[:2]

I get almost the same error as mentioned in the comments: Cannot reorder a query once a slice has been taken.


Try overriding this instead:

def get_dated_items(self):
    date_list, items, extra_context = super(MainIndex, self).get_dated_items()
    return (date_list, items[:2], extra_context)
Note: this implementation may leave the date_list inconsistent with the items query set after the latter is sliced. I think that to fix that you would need to regenerate date_list too. see the implementation of BaseArchiveIndexView.get_dated_items in SVN for more details: http://code.djangoproject.com/browser/django/trunk/django/views/generic/dates.py. Something like this might work:
def get_dated_items(self):
    date_list, items, extra_context = super(MainIndex, self).get_dated_items()
    items = items[:2]
    date_list = self.get_date_list(items, 'year')
    if not date_list:
        items = items.none()
    return (date_list, items, extra_context)
but if it works without this, I would not touch it because it looks too messy.


I ran into this exact problem myself. I've found that using ListView (instead of ArchiveIndexView) for this saved me time and hassle.

For your first chunk of code, the difference would be:

from django.views.generic import ListView


url(r'^$', 
    ListView.as_view(
        model = Entry,
        context_object_name = 'entry_list',
        template_name = 'news/news.html',
        queryset=Entry.objects.all().order_by("-published")[:2],
    ), name = 'archive_index'
),
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜