Why Django Rest Framework (DRF), permission_classes is a list

In Django Rest Framework (DRF), permission_classes is a list because it allows you to specify multiple permission classes that the view should enforce. The idea is that a request must pass all of the permissions in the list for access to be granted. Even if you are using just one permission class, such as IsAuthenticated, it is still defined as a list for consistency and extensibility.

Explanation:

  • permission_classes = [IsAuthenticated]:
    • This means that only authenticated users will be allowed to access the view.
    • If more permission checks are needed (e.g., to restrict access to admins or object owners), you can easily add other permission classes to the list.
  • Why a List?
    • Multiple permissions: DRF can enforce multiple permission checks by adding them as list elements. For example
permission_classes = [IsAuthenticated, IsAdminUser]

This setup would require the user to be both authenticated and an admin to access the view.Extensibility: Using a list allows flexibility for future additions. If you initially set permission_classes = [IsAuthenticated], it’s easy to add more permissions later as needed.

from rest_framework.permissions import IsAuthenticated, IsAdminUser
from rest_framework import generics
from .serializers import NoteSerializer
from .models import Note

class NoteListCreateView(generics.ListCreateAPIView):
    queryset = Note.objects.all()
    serializer_class = NoteSerializer
    permission_classes = [IsAuthenticated]  # Only authenticated users can access this view
class NoteAdminListView(generics.ListAPIView):
    queryset = Note.objects.all()
    serializer_class = NoteSerializer
    permission_classes = [IsAuthenticated, IsAdminUser]  # Only authenticated admins can access this view

Leave a Reply

Your email address will not be published. Required fields are marked *

Deprecated: htmlspecialchars(): Passing null to parameter #1 ($string) of type string is deprecated in /var/www/html/wp-includes/formatting.php on line 4720