Skip to content
This repository has been archived by the owner on Sep 17, 2023. It is now read-only.

08 Class based views

scotwk edited this page May 10, 2015 · 2 revisions

The first two views are examples of function-based views. Django has a new object-oriented view system called class-based views.

Class-based views can significantly reduce the code needed for doing simple views, as well as allowing you to easily share code between views by using object inheritance.

We won't change any functionality in this chapter, but we'll change our views to class-based views.

Modify views

note/views.py should now look like:

from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
from django.views.generic import ListView, DetailView

from .models import Note


class NoteList(ListView):
    paginate_by = 5
    template_name = 'note/index.html'
    context_object_name = 'latest_note_list'

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super(NoteList, self).dispatch(*args, **kwargs)

    def get_queryset(self):
        return Note.objects.filter(owner=self.request.user)


class NoteDetail(DetailView):
    model = Note
    template_name = 'note/detail.html'
    context_object_name = 'note'

    @method_decorator(login_required)
        def dispatch(self, *args, **kwargs):
            return super(NoteDetail, self).dispatch(*args, **kwargs)

Update URLs

Also, update the note/urls.py file to reference your new CBVs. CBVs have an as_view() method to return the view.

from .views import NoteList, NoteDetail

...

url(r'^$', NoteList.as_view(), name='index'),
url(r'^(?P<pk>[0-9]+)/$', NoteDetail.as_view(), name='detail'),

A handy resource for working with CBVs is Classy CBV.