我不清楚在Django 1.5的基于类的视图中最佳方法是如何访问URL参数。
考虑以下内容:
视图:
from django.views.generic.base import TemplateView
class Yearly(TemplateView):
template_name = "calendars/yearly.html"
current_year = datetime.datetime.now().year
current_month = datetime.datetime.now().month
def get_context_data(self, **kwargs):
context = super(Yearly, self).get_context_data(**kwargs)
context['current_year'] = self.current_year
context['current_month'] = self.current_month
return context
URLCONF:
from .views import Yearly
urlpatterns = patterns('',
url(
regex=r'^(?P<year>\d+)/$',
view=Yearly.as_view(),
name='yearly-view'
),
)
我想在我的视图中访问year
参数,以便可以执行以下逻辑:
month_names = [
"January", "February", "March", "April",
"May", "June", "July", "August",
"September", "October", "November", "December"
]
for month, month_name in enumerate(month_names, start=1):
is_current = False
if year == current_year and month == current_month:
is_current = True
months.append({
'month': month,
'name': month_name,
'is_current': is_current
})
如何在像上面这样的继承了TemplateView
的类中访问最佳的url参数,以及在哪里理想地放置这样的逻辑,例如在一个方法中?
django2
中有一个简单的extra_context
字典选项,详情请见这里。 - Timo