Django · Lesson 12 of 15
DRF Auth, Permissions and Pagination
Token and session auth, permissions, filtering and pagination in DRF.
- Advanced
- 16 min read
- 3 objectives
Before this lessonLesson 11: Static Files, Media and Caching
What you will learn
- Protect a viewset
- Paginate a list
- Filter with query params
Your Progress
0 of 15 lessons 0%
- Lessons0 / 15
- Completed0
- Est. time left~ 4 hours
Create a free account to keep your progress on every device.
Django REST framework's viewsets become production APIs when you add authentication, permissions, pagination and filters.
Authentication and permissions
# settings.py
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": [
"rest_framework.authentication.SessionAuthentication",
"rest_framework.authentication.TokenAuthentication",
],
"DEFAULT_PERMISSION_CLASSES": [
"rest_framework.permissions.IsAuthenticatedOrReadOnly",
],
"DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination",
"PAGE_SIZE": 20,
}from rest_framework.permissions import IsAuthenticated, IsOwnerOrReadOnly
from rest_framework.viewsets import ModelViewSet
class PostViewSet(ModelViewSet):
queryset = Post.objects.select_related("author")
serializer_class = PostSerializer
permission_classes = [IsAuthenticated]
def perform_create(self, serializer):
serializer.save(author=self.request.user)Filtering and search
from rest_framework.filters import SearchFilter, OrderingFilter
from django_filters.rest_framework import DjangoFilterBackend
class PostViewSet(ModelViewSet):
filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
filterset_fields = ["published", "author"]
search_fields = ["title", "body"]
ordering_fields = ["created"]Throttling
"DEFAULT_THROTTLE_RATES": {"anon": "20/min", "user": "100/min"}