How to use Class-Based View in Django

Mostly of use  start in Django with  humble function-based view  ,they are good and easy to understand . It was a simple time. Views would take a request and return a response . But problems was in  large projects where with  function-based view  we have lots of similar views.   In Django 1.3 appear  Class-Based View which makes Django  pogramming for large project  better and faster..In this article we'll show you how to use Class-Based View.

from django.views.generic import ListView

from django.shortcuts import get_object_or_404

class BaseView(ListView):   
    context_object_name = 'content'

    def get_context_data(self, **kwargs):
        context = super(BaseView, self).get_context_data(**kwargs)
        context['logged'] = self.request.session.get("logged","")
        context['meta_title'] = self.meta_title
        context['meta_descr'] = self.meta_descr
        return context

class FunnyImages(BaseView):
    queryset =  get_object_or_404(MyContent, id=2)
    meta_title="Funny Images"
    meta_descr="List of best funny images about programming!"


class SimilarSites(BaseView):
    queryset =  get_object_or_404(MyContent, id=3)
    meta_title="Similar Sites"
    meta_descr="List of similar sites!"

def get_context_data  override default method and add extra variables to context, and we get additional information in template

template_name tell the view which templates to use , but in the absence of an explicit template Django will infer one from the object’s name.

context_object_name attribute on a generic view specifies the context variable to use, so in template we'll use {{content}}

queryset get information from database, in template we get that data with {{content}} variable

get_object_or_404 is django shortcut function

url(r'^funnyimages/$', FunnyImages.as_view()),
url(r'^friendsites/$', SimilarSites.as_view()),




Useful Links : Dec. 26, 2014, 4:12 p.m.