Class Based Views Part 1: TemplateView and RedirectView

This is the first episode in a series of videos on Class Based generic Views. These are important to learn since the function based generic views are being deprecated, and Class Based generic Views will help to streamline things moving forward when dealing with views. This video goes over the most basic views, TemplateView and RedirectView. The video uses simple scenarios, but usable, to get you started.
from django.conf.urls import patterns, url
from django.views.generic import TemplateView

from views import DisplayTaskView, DisplayTaskRedirectView

urlpatterns = patterns('',
    url(r'^(?P<task_id>\d+)-(?P<slug>[-\w]+)/$', DisplayTaskView.as_view()),
    url(r'^(?P<task_id>\d+)/$', DisplayTaskRedirectView.as_view()),
    url(r'^$', TemplateView.as_view(template_name='todo/index.html')),
from django.views.generic import TemplateView, RedirectView

from models import Task

class DisplayTaskView(TemplateView):
    template_name = "todo/task.html"

    def get_context_data(self, kwargs):
        context = super(DisplayTaskView, self).get_context_data(kwargs)
        context['task'] = Task.objects.get(pk=self.kwargs.get('task_id', None))
        return context

class DisplayTaskRedirectView(RedirectView):

    def get(self, request, args, **kwargs):
        task_id = self.kwargs.get('task_id', None)
        task = Task.objects.get(pk=task_id)
        self.url = '/todo/%s-%s' % (, task.slug)
        return super(DisplayTaskRedirectView, self).get(request, args, **kwargs)
comments powered by Disqus