一尘不染

基于Django类的视图(TemplateView)中的URL参数和逻辑

django

我不清楚在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
        })

例如,如何最好地访问CBV中被子类化的url参数,TemplateView理想情况下应将逻辑放置在哪里?在某种方法上?


阅读 648

收藏
2020-03-30

共1个答案

一尘不染

要在基于类的视图中访问url参数,请使用self.args或,self.kwargs这样你就可以通过self.kwargs['year']

2020-03-30