Django: Checking for User Permissions

I found it a little difficult finding solid information about implementing user permission checks for Django.

After reading numerous sites and tutorials, I've combined a few methods to make it a bit easier.

Rather than inserting the permissions into the database manually, use the Meta attribute in your models (from Satchmo Project).

class Caption(models.Model):
Example model with permission.
# Your field declarations
title = model.TextField()
description = model.TextField()

class Meta:
permissions = (
("is_caption_moderator", "Caption Moderator"),

After setting up the permissions, use ./ syncdb to install these permissions into the database.

Now you can simply check for sufficient permissions as long as you have the user object.

def your_view(request):
if request.user.has_perm('is_caption_moderator') == False:
# Do something here like return HttpResponseNotAllowed()

# The rest of your view here

Lastly, remember to grant specific permissions to users when moving this code live because the admin user automatically has access to everything.


Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog