How to Use @permission_required Decorator in Django
Use the
@permission_required decorator in Django to restrict access to views based on user permissions by specifying the permission string like 'app_label.permission_codename'. It automatically redirects unauthorized users to the login page or shows a 403 error if configured.Syntax
The @permission_required decorator is used above a view function to check if the logged-in user has a specific permission.
It takes two main arguments:
perm: A string with the format'app_label.permission_codename'representing the required permission.login_url(optional): URL to redirect unauthorized users to login.raise_exception(optional): IfTrue, raises a 403 Forbidden error instead of redirecting.
python
@permission_required('app_label.permission_codename', login_url=None, raise_exception=False) def my_view(request): # view code here pass
Example
This example shows how to protect a view so only users with the polls.can_vote permission can access it. Unauthorized users are redirected to the login page.
python
from django.contrib.auth.decorators import permission_required from django.http import HttpResponse @permission_required('polls.can_vote') def vote(request): return HttpResponse('You can vote!')
Output
If user has 'polls.can_vote' permission: Displays 'You can vote!'. Otherwise: Redirects to login page.
Common Pitfalls
- Not specifying the correct permission string format
'app_label.permission_codename'causes the decorator to fail silently. - Using
@permission_requiredon class-based views without adapting it properly will not work. - For APIs or JSON responses, redirecting to login may not be appropriate; use
raise_exception=Trueto get a 403 error instead. - For anonymous users, the decorator redirects to login by default, so ensure your login URL is set correctly.
python
from django.contrib.auth.decorators import permission_required from django.http import HttpResponse # Wrong: missing app label or wrong permission codename @permission_required('can_vote') # Incorrect def vote_wrong(request): return HttpResponse('Wrong permission string') # Right: full permission string @permission_required('polls.can_vote') def vote_right(request): return HttpResponse('Correct permission string')
Quick Reference
| Parameter | Description | Default |
|---|---|---|
| perm | Permission string in 'app_label.permission_codename' format | Required |
| login_url | URL to redirect unauthorized users to login | None (uses settings.LOGIN_URL) |
| raise_exception | If True, raises 403 error instead of redirecting | False |
Key Takeaways
Use @permission_required with the full permission string 'app_label.permission_codename'.
By default, unauthorized users are redirected to the login page.
Set raise_exception=True to return a 403 Forbidden error instead of redirecting.
Ensure your login URL is correctly configured in Django settings.
@permission_required works only on function-based views or needs adaptation for class-based views.