Permissions

Back

Loading concept...

Django Authentication: Permissions 🔐

The Nightclub Bouncer Story

Imagine a fancy nightclub with different areas. There’s the main dance floor (everyone can enter), the VIP lounge (only VIP members), the DJ booth (only staff), and the owner’s office (only the owner). Django’s permission system works exactly like the bouncers at this club!


What Are Permissions?

Permissions are rules that decide who can do what in your app.

Think of it this way:

  • Can this person see the menu? (View permission)
  • Can this person add new items? (Add permission)
  • Can this person change prices? (Change permission)
  • Can this person delete items? (Delete permission)

Django gives you these 4 bouncers (permissions) for FREE for every model you create!


1. User Permissions 👤

What Are User Permissions?

User permissions are like personal badges you give to each person. If Sarah has a “can_edit_blog” badge, she can edit blogs. If Tom doesn’t have it, he can’t!

How Django Creates Permissions Automatically

When you create a model, Django automatically makes 4 permissions:

# Your model
class Article(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()

Django creates these badges automatically:

  • app_name.add_article - Can add new articles
  • app_name.change_article - Can edit articles
  • app_name.delete_article - Can delete articles
  • app_name.view_article - Can view articles

Giving Badges to Users

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

# Find the user
user = User.objects.get(username='sarah')

# Find the permission badge
permission = Permission.objects.get(
    codename='change_article'
)

# Give Sarah the badge!
user.user_permissions.add(permission)

Checking If User Has a Badge

# Does Sarah have the edit badge?
if user.has_perm('blog.change_article'):
    print("Sarah can edit articles!")
else:
    print("Sorry Sarah, no editing for you!")

Real Example: A Blog App

# Give Sarah multiple badges at once
sarah.user_permissions.add(
    add_permission,
    change_permission,
    view_permission
)

# Check multiple permissions
if sarah.has_perms([
    'blog.add_article',
    'blog.change_article'
]):
    print("Sarah is a writer!")

2. Groups 👥

What Are Groups?

Groups are like team jerseys. Instead of giving badges one by one, you put people on teams!

Imagine:

  • Team Writers - Can add and edit articles
  • Team Editors - Can add, edit, and delete articles
  • Team Viewers - Can only view articles

When you join a team, you get ALL the team’s badges automatically!

graph TD A["Admin Group"] --> P1["Add Permission"] A --> P2["Change Permission"] A --> P3["Delete Permission"] A --> P4["View Permission"] B["Editor Group"] --> P2 B --> P4 C["Viewer Group"] --> P4 U1["Alice"] --> A U2["Bob"] --> B U3["Charlie"] --> C

Creating a Team (Group)

from django.contrib.auth.models import Group

# Create the Writers team
writers_group = Group.objects.create(
    name='Writers'
)

# Give the team some badges
writers_group.permissions.add(
    add_article_perm,
    change_article_perm
)

Adding Users to Teams

# Sarah joins the Writers team
sarah.groups.add(writers_group)

# Now Sarah automatically has:
# - add_article permission
# - change_article permission

Why Groups Are Amazing

Without Groups (Messy!):

# Adding 10 permissions to 100 users = 1000 operations!
for user in all_users:
    user.user_permissions.add(perm1, perm2, ...)

With Groups (Clean!):

# Create group once with 10 permissions
# Add 100 users to group = 100 operations!
for user in all_users:
    user.groups.add(writers_group)

3. Permission Decorators 🎀

What Are Decorators?

Decorators are like automatic bouncers at the door. They check your badge BEFORE you can enter!

Think of it as a sign on a door that says: “Stop! Show your badge first!”

The @login_required Decorator

The simplest bouncer - just checks if you’re logged in:

from django.contrib.auth.decorators import login_required

@login_required
def my_secret_page(request):
    return render(request, 'secret.html')

If not logged in → Bouncer sends you to login page!

The @permission_required Decorator

This bouncer checks for a SPECIFIC badge:

from django.contrib.auth.decorators import permission_required

@permission_required('blog.add_article')
def create_article(request):
    # Only people with 'add_article' badge enter!
    return render(request, 'create.html')

Checking Multiple Badges

@permission_required(
    ['blog.add_article', 'blog.change_article'],
    raise_exception=True
)
def manage_articles(request):
    # Need BOTH badges to enter!
    return render(request, 'manage.html')

Custom Redirect When Badge Missing

@permission_required(
    'blog.delete_article',
    login_url='/no-access/'
)
def delete_article(request, id):
    # No badge? Go to /no-access/ page!
    pass

For Class-Based Views

from django.contrib.auth.mixins import PermissionRequiredMixin

class ArticleCreateView(PermissionRequiredMixin, CreateView):
    permission_required = 'blog.add_article'
    model = Article
    # Same bouncer, different style!

4. Object-Level Permissions 🎯

What Are Object-Level Permissions?

Regular permissions say: “Can Sarah edit ANY article?”

Object-level permissions say: “Can Sarah edit THIS SPECIFIC article?”

The Difference

graph TD subgraph Model Level A["Can edit articles?"] --> B["Yes = Edit ALL"] A --> C["No = Edit NONE"] end subgraph Object Level D["Can edit Article #5?"] --> E["Yes = Edit #5 only"] D --> F[No = Can't edit #5] end

Model-Level: “Sarah can edit articles” = ALL articles Object-Level: “Sarah can edit HER OWN articles” = Only specific ones

Django Doesn’t Have This Built-In!

Django’s default permissions are model-level only. For object-level, you need help!

Popular helper: django-guardian

pip install django-guardian

Using django-guardian

Setup:

# settings.py
INSTALLED_APPS = [
    ...
    'guardian',
]

AUTHENTICATION_BACKENDS = [
    'django.contrib.auth.backends.ModelBackend',
    'guardian.backends.ObjectPermissionBackend',
]

Assigning Object Permission:

from guardian.shortcuts import assign_perm

# Sarah can edit ONLY this specific article
article = Article.objects.get(id=5)
assign_perm('change_article', sarah, article)

Checking Object Permission:

from guardian.shortcuts import get_perms

# Can Sarah edit article #5?
if 'change_article' in get_perms(sarah, article):
    print("Sarah can edit this one!")

Real-World Example: Blog Ownership

# When user creates an article,
# give them permission to that article

def create_article(request):
    article = Article.objects.create(
        title=request.POST['title'],
        author=request.user
    )

    # Owner gets full control of THEIR article
    assign_perm('change_article', request.user, article)
    assign_perm('delete_article', request.user, article)

    return redirect('article_detail', article.id)

Common Pattern: Ownership Check

Sometimes you don’t need a whole library!

def edit_article(request, article_id):
    article = Article.objects.get(id=article_id)

    # Simple ownership check
    if article.author != request.user:
        return HttpResponseForbidden("Not yours!")

    # Continue with editing...

Quick Summary 📝

Feature What It Does Example
User Permissions Give badges to individual users Sarah can edit
Groups Give badges to teams All Writers can edit
Decorators Auto-check badges at door @permission_required
Object-Level Control specific items Sarah edits HER posts

The Complete Picture

graph TD U["User"] --> UP["User Permissions"] U --> G["Groups"] G --> GP["Group Permissions"] UP --> C{Permission Check} GP --> C C -->|Has Permission| A["Access Granted!"] C -->|No Permission| D["Access Denied!"] A --> OLP{Object-Level?} OLP -->|Yes| O["Check Specific Object"] OLP -->|No| S["Access to All"]

Key Takeaways 🎉

  1. User Permissions = Personal badges for individuals
  2. Groups = Teams that share badges (much cleaner!)
  3. Decorators = Automatic bouncers on your views
  4. Object-Level = Fine control over specific items

Remember: Django gives you the nightclub bouncers. You decide who gets VIP access! 🎊

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.