Class Based Views Part 1: TemplateView and RedirectView

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.

15. Class Based Views Part 1: TemplateView and RedirectView
Apr 04, 2012 - 14 minutes
Download: mp4 | webm
comments powered by Disqus

todo/urls.py
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')),
)
todo/views.py
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.id, task.slug)
        return super(DisplayTaskRedirectView, self).get(request, *args, **kwargs)

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.