0

在使用 Django 的基于日期的通用视图时,我不想在详细视图的 URL 中有一天。我尝试了以下但得到TypeError at /logbook/2013/january/testing/ object_detail() takes at least 6 arguments (7 given)

模型.py

class Entry(models.Model):
    pub_date = models.DateTimeField()

def get_absolute_url(self):
    return "/logbook/%s/%s/" % (self.pub_date.strftime("%Y/%B").lower(), self.slug)

网址.py:

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

from .models import Entry
from . import views

urlpatterns += patterns('',
    url(r'^logbook/(?P<year>\d{4})/(?P<month>[A-Za-z]+)/(?P<slug>[\w-]+)/$', 
    views.entry_detail),
)

视图.py:

import functools
from django.views.generic import date_based

from .models import Entry

def prepare_arguments(view):
    @functools.wraps(view)
    def wrapped(request, *args, **kwargs):
        kwargs['allow_future'] = request.user.is_staff
        kwargs['queryset'] = Entry.objects.all() if request.user.is_staff 
        else Entry.objects.published()
        kwargs['date_field'] = 'pub_date'
        return view(request, *args, **kwargs)
    return wrapped

@prepare_arguments
def entry_detail(request, *args, **kwargs):
    return date_based.object_detail(request, *args, **kwargs)

是否可以修改上面的代码并继续使用基于 date_based 的通用视图,而 URL 中没有日期?如果没有,有人可以举一个 URL 模式的简单自定义视图的例子url(r'^logbook/(?P<year>\d{4})/(?P<month>[A-Za-z]+)/(?P<slug>[\w-]+)/$', views.entry_detail)吗?

4

1 回答 1

0

感谢Alasdair为我指明了正确的方向和ccbv.co.uk。我最终使用了DetailView并且这很有效:

网址.py:

from django.views.generic import DetailView

urlpatterns += patterns('',
    url(r'^logbook/(?P<year>\d+)/(?P<month>[-\w]+)/(?P<slug>[\w-]+)/$',
        DetailView.as_view(model=Entry),
        name="entry_detail"),
)

视图.py:

# nothing needed here for the detail view to work, though in the future 
# I would like to have the generic view code here instead to accomplish 
# the same thing as `DetailView.as_view(model=Entry), name="entry_detail"` 
# in urls.py, and would appreciate an example of this.
于 2013-01-08T13:40:19.673 回答