2014-09-07

Leverage Django Permission System

Django comes with a simple permission system which is used by the Django admin site. The doc says we can use the Django permission system in our own code as well.
How can we leverage the Django Permission System for our own use? One way is to create an app specifically for the purpose, and use a model to create the custom permissions that we need.
For example, if we want a user to have "export" permission in order to export data, and "download" permission in order to download stuff, then we can create an app called "permission" with a model called "Permission", and add custom permissions to it.
After adding the "permission" app to INSTALLED_APPS in settings.py and run syncdb, we can then use Django admin site to assign permission to a user, or better yet assign permissions to a group and then assign users to the group. Then we can check if a user has "export" or "download" permission by using the Django permission system.
Creating an app for this purpose may be an overkill, but I found it modular in design and easy to maintain.

=== permission/models.py ===

from django.db import models

class Permission(models.Model):
    class Meta:
        permissions = (
            ("export", "Can export data"),
            ("download", "Can download stuff"),
        )

=== settings.py ===

INSTALLED_APPS = (
    ...
    'permission',
)

=== Usage ===

from django.contrib.auth.models import User
john = User.objects.get(username='john')
john.has_perm("permission.export")

or

@permission_required('permission.export')
def some_view(request):
    ...

-End-

No comments: