Django: Generic Class Based Views with Object Level Permissions Checking

A common design pattern in Django Class Based Views (CBVs) is checking whether the user is logged-in (authenticated) or not. If the user is authenticated, the view proceeds. If not, the view throws a permission denied exception. A common security feature in web sites.

For example, take a look at this code:

from django.contrib.auth.models import User
from django.db import models

class Blog(models.Model):
    title = models.CharField(max_length=255)
    user = models.ForeignKey(User)

from django.views.generic.edit import UpdateView

from models import Blog

class BlogUpdateView(UpdateView):
    model = Blog

from django.conf.urls.defaults import *
from django.contrib.auth.decorators import login_required

from views import BlogUpdateView

urlpatterns = patterns("views",

The is a common place to put these constraints. In here, only logged-in users are allowed to edit blog entries. Great!

But consider this scenario. Darwin logs-in, creates his blog, and then saves it. Mel happens to log-in, creates her blog, and saves it. Now two blog objects exist with IDs let’s say 1 for Darwin and 2 for Mel. Darwin tries to hack Mel’s blog and types the following address in his browser.

Remember that the codes above allow any logged-in user access to the view BlogUpdateView. Darwin could actually edit Mel’s blog entry and save his changes. Terrible!

Enter dslibpy.views.restricted

As a solution to the problem, I have rolled-out dslibpy.views.restricted. A set of “secure” Class Based Views that subclass each of the view classes in django.views.generic. I compiled the modules as part of a larger library of Python reusable codes. You can subclass these views in your projects to add restrictions to your views.

Here is the full documentation for dslibpy.views.restricted.

Installing dslibpy

dslibpy is absolutely free! You may use it, modify it, and redistribute it. The dslibpy documentation contains instructions on how to install dslibpy.


It worked!

Bookmark the permalink.

One Comment

  1. Thanks for sharing. Your post is a useful cobiitnutron.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.