Labs ICT
⭐ Pro Login

Permissions

Who can do what in your app.

2 min read | Django Tutorial
⭐

Want the full learning experience?

Get structured courses, certificates, projects, and instructor support with LabsICT Pro.

Explore Pro Courses

Understanding Permissions

Django's permission system lets you control what users can do. Every model gets four default permissions: add, change, delete, and view.


user.has_perm('app.add_post')
user.has_perm('app.change_post')
user.has_perm('app.delete_post')
user.has_perm('app.view_post')
    

Use has_perm() to check if a user has a specific permission. Returns True or False.

Custom Permissions

You can define custom permissions on your models for fine-grained access control.


from django.db import models

class Article(models.Model):
    title = models.CharField(max_length=200)
    author = models.ForeignKey('auth.User', on_delete=models.CASCADE)

    class Meta:
        permissions = [
            ('can_publish', 'Can publish articles'),
            ('can_feature', 'Can feature articles on homepage'),
        ]
    

Custom permissions appear in the admin under the User permissions section. You can check them with user.has_perm('app.can_publish').

Using Permissions in Views

Check permissions in your views to control access to specific actions.


from django.contrib.auth.decorators import permission_required

@permission_required('app.can_publish', raise_exception=True)
def publish_article(request, pk):
    article = get_object_or_404(Article, pk=pk)
    article.is_published = True
    article.save()
    return redirect('article_detail', pk=pk)
    

The @permission_required decorator checks permissions and returns 403 Forbidden if the user doesn't have them.

Groups and Object-Level Permissions

Groups let you assign permissions to multiple users at once. Object-level permissions control access to specific instances.


from django.contrib.auth.models import Group, Permission

editors = Group.objects.create(name='Editors')
can_publish = Permission.objects.get(codename='can_publish')
editors.permissions.add(can_publish)

user.groups.add(editors)
    

For object-level permissions, you can use libraries like django-guardian to check permissions on individual objects.

Checking Module Permissions

Use has_module_perms() to check if a user has any permissions for a specific app.


if user.has_module_perms('blog'):
    # User can access the blog app
    pass
    

This is useful for hiding entire apps from the admin sidebar or navigation menus based on user permissions.