基于Django类的视图中的URL参数和逻辑(TemplateView) [英] URL-parameters and logic in Django class-based views (TemplateView)
问题描述
请考虑以下内容:
查看:
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
返回上下文
URLCONF:
from .views import Yearly
urlpatterns = patterns('',
url(
regex = r'^(?P< year> \d +)/ $',
view = Yearly.as_view(),
name ='yearly-view '
),
)
我想访问我的视图中的年份
参数,所以我可以做如下逻辑:
code> month_names = [1月,二月,三月,四月,五月,六月,七月,
八月,九月 ,十一月,十二月]
为月,月名为枚举(month_names,start = 1):
is_current = False
如果year == current_year和month == current_month:
is_current = True
months.append({
'month':month,
'name':month_name,
'is_current':is_current} )
如何最好访问CBV中的url参数,像上面那样的 TemplateView
,应该在哪里理想地放置这样的逻辑,例如。在方法中?
要在基于类的视图中访问url参数,请使用 self.args
或 self.kwargs
所以你可以通过执行 self.kwargs ['year']
It is unclear to me how it is best to access URL-parameters in class-based-views in Django 1.5.
Consider the following:
View:
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'
),
)
I want to access the year
parameter in my view, so I can do logic like:
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})
How would one best access the url parameter in CBVs like the above that is subclassed of TemplateView
and where should one ideally place the logic like this, eg. in a method?
To access the url parameters in class based views, use self.args
or self.kwargs
so you would access it by doing self.kwargs['year']
这篇关于基于Django类的视图中的URL参数和逻辑(TemplateView)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!