0
0
Djangoframework~5 mins

Permission required decorator in Django

Choose your learning style9 modes available
Introduction

The permission required decorator helps you control who can access certain parts of your Django app. It makes sure only users with the right permissions can see or use specific views.

When you want to restrict access to a page only to users with a specific permission.
When you want to protect sensitive data or actions in your web app.
When you want to avoid writing manual permission checks inside your view functions.
When you want to keep your code clean and easy to read by using decorators.
When you want to redirect unauthorized users to a login or error page automatically.
Syntax
Django
@permission_required('app_label.permission_codename', login_url=None, raise_exception=False)
def your_view(request):
    # view code here

The decorator takes the permission as a string in the format 'app_label.permission_codename'.

You can set login_url to redirect unauthorized users to a custom page.

Examples
This view only allows users with the 'add_choice' permission in the 'polls' app.
Django
@permission_required('polls.add_choice')
def add_choice(request):
    # code to add a choice
Redirects unauthorized users to '/login/' if they lack the 'change_user' permission.
Django
@permission_required('auth.change_user', login_url='/login/')
def edit_user(request):
    # code to edit user
Raises a 403 error instead of redirecting if the user lacks permission.
Django
@permission_required('blog.delete_post', raise_exception=True)
def delete_post(request):
    # code to delete a post
Sample Program

This simple Django view uses the permission required decorator to allow only users with the 'view_poll' permission in the 'polls' app to access it. If the user does not have permission, they are redirected to '/login/'.

Django
from django.contrib.auth.decorators import permission_required
from django.http import HttpResponse

@permission_required('polls.view_poll', login_url='/login/')
def view_poll(request):
    return HttpResponse('You can see this poll because you have permission!')
OutputSuccess
Important Notes

Make sure the permission codename matches exactly what is defined in your app's models.

If you set raise_exception=True, unauthorized users get a 403 Forbidden error instead of redirect.

Use this decorator only on views that require user authentication and permission checks.

Summary

The permission required decorator controls access to views based on user permissions.

It helps keep your code clean and secure by handling permission checks automatically.

You can customize behavior for unauthorized users with login_url or raise_exception.