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
passClick 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?✗ Incorrect
The permission must be specified as 'app_label.permission_codename', for example 'polls.can_vote'.
What does setting
raise_exception=True in @permission_required do?✗ Incorrect
Setting raise_exception=True causes Django to raise a 403 Forbidden error instead of redirecting.
Which import is needed to use
@permission_required?✗ Incorrect
The decorator is imported from django.contrib.auth.decorators.
If you want to protect a class-based view with permissions, what should you use?
✗ Incorrect
PermissionRequiredMixin is designed for class-based views to enforce permissions.
What happens if an anonymous user accesses a view with
@permission_required?✗ Incorrect
Anonymous users are redirected to the login page by default.
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.