我不清楚在 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
返回文章页面
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
})
如何最好地访问像上面这样的 CBV 中的 url 参数,它是 TemplateView
的子类,以及理想情况下应该将这样的逻辑放在哪里,例如放在一个方法中?