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.

views.py

from django.views.generic import ListView

from django.shortcuts import get_object_or_404

class BaseView(ListView):   
    context_object_name = 'content'
    template_name='askme/content.html'
    meta_title="Home"
    meta_descr=""

    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 https://docs.djangoproject.com/en/1.7/topics/http/shortcuts/#get-object-or-404

 

urls.py

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

 

 

 

Useful Links : 

 

https://docs.djangoproject.com/en/1.7/topics/class-based-views/generic-display/

https://github.com/django/django/tree/master/django/views/generic

http://ccbv.co.uk/

 

email@djangotutsme.com Dec. 26, 2014, 4:12 p.m.