URL-parameters and logic in Django class-based views (TemplateView)

user1319936 picture user1319936 · Apr 2, 2013 · Viewed 96.1k times · Source

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?

Answer

Ngenator picture Ngenator · Apr 2, 2013

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']