我有一个MonthArchiveView用于我网站上的活动。如果没有提交年份和月份(例如,如果用户只访问/ events /?
,如何将存档默认设置为当前月份而不是提出例外情况?# urls.py
url(r'^events/$', EventMonthView.as_view(), name="event_month"),
url(r'^events/(?P<year>[0-9]{4})/(?P<month>[0-9]+)/$', EventMonthView.as_view(month_format='%m'), name="event_month"),
#views.py
class EventMonthView(MonthArchiveView):
template_name = "events.html"
queryset = Event.objects.all()
date_field = "date"
allow_future = True
month_format='%m'
year_format='%Y'
答案 0 :(得分:3)
您可以覆盖get_month
和get_year
方法,以便它们返回默认值:
from django.http import Http404
from django.utils.timezone import now
from django.views.generic import MonthArchiveView
class EventMonthView(MonthArchiveView):
# ...
def get_month(self):
try:
month = super(EventMonthView, self).get_month()
except Http404:
month = now().strftime(self.get_month_format())
return month
def get_year(self):
try:
year = super(EventMonthView, self).get_year()
except Http404:
year = now().strftime(self.get_year_format())
return year