在使用Django的dated_based generic views时,我不希望在详细视图的URL中显示这一天。我尝试了以下操作,但获得TypeError at /logbook/2013/january/testing/ object_detail() takes at least 6 arguments (7 given)
:
models.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)
urls.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),
)
views.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)
是否可以修改上面的代码并继续使用不带URL日期的date_based通用视图?如果没有,有人可以举例说明网址格式url(r'^logbook/(?P<year>\d{4})/(?P<month>[A-Za-z]+)/(?P<slug>[\w-]+)/$', views.entry_detail)
的简单自定义视图吗?
答案 0 :(得分:0)
感谢Alasdair指出我正确的方向和ccbv.co.uk。我最终使用了DetailView,这很有效:
<强> urls.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"),
)
<强> views.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.