0
0
Djangoframework~5 mins

Permission required decorator in Django - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of the @permission_required decorator in Django?
It restricts access to a view so that only users with a specific permission can use it. If the user lacks the permission, they are redirected or shown an error.
Click to reveal answer
beginner
How do you specify which permission a Django view requires using @permission_required?
You pass the permission as a string argument in the format 'app_label.permission_codename' to the decorator.
Click to reveal answer
intermediate
What happens if a user without the required permission tries to access a view decorated with @permission_required?
By default, the user is redirected to the login page. You can change this behavior by setting the raise_exception=True argument to show a 403 Forbidden error instead.
Click to reveal answer
beginner
Write a simple example of using @permission_required to require the permission polls.can_vote on a view.
from django.contrib.auth.decorators import permission_required

@permission_required('polls.can_vote')
def vote(request):
    # view code here
    pass
Click to reveal answer
intermediate
Can @permission_required be used with class-based views in Django?
Not directly. You can use the PermissionRequiredMixin from django.contrib.auth.mixins to enforce permissions on class-based views.
Click to reveal answer
What argument format does @permission_required expect for the permission?
A'permission_codename'
B'permission_codename.app_label'
C'app_label.permission_codename'
D'app_label'
What does setting raise_exception=True in @permission_required do?
ARedirects to login page
BRaises a 403 Forbidden error
CGrants permission automatically
DLogs the user out
Which import is needed to use @permission_required?
Afrom django.contrib.auth.decorators import permission_required
Bfrom django.shortcuts import permission_required
Cfrom django.views.decorators import permission_required
Dfrom django.contrib.auth.mixins import permission_required
If you want to protect a class-based view with permissions, what should you use?
ANo protection needed
B@permission_required decorator
Clogin_required decorator
DPermissionRequiredMixin
What happens if an anonymous user accesses a view with @permission_required?
AThey are redirected to login page
BThey get access anyway
CThey see a 404 error
DThey get a 500 server error
Explain how the @permission_required decorator works in Django and how you use it in a function-based view.
Think about how you protect a view so only certain users can use it.
You got /5 concepts.
    Describe the difference between using @permission_required and PermissionRequiredMixin in Django.
    Consider the type of view you want to protect.
    You got /5 concepts.