Django
Beginner
1 min read
ModelViewSet, Routers, and DRF Authentication
Example
# blog/api/views.py — ModelViewSet
from rest_framework import viewsets, permissions
from rest_framework.decorators import action
from rest_framework.response import Response
from ..models import Post
from ..serializers import PostSerializer
class PostViewSet(viewsets.ModelViewSet):
queryset = Post.objects.select_related('author').order_by('-published_at')
serializer_class = PostSerializer
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
def get_queryset(self):
qs = super().get_queryset()
if self.action == 'list':
qs = qs.filter(status=Post.STATUS_PUBLISHED)
return qs
def perform_create(self, serializer):
serializer.save(author=self.request.user)
# Custom action: GET /api/posts/my/
@action(detail=False, methods=['get'], permission_classes=[permissions.IsAuthenticated])
def my(self, request):
posts = Post.objects.filter(author=request.user)
serializer = self.get_serializer(posts, many=True)
return Response(serializer.data)
# blog/api/urls.py — router-based URL registration
from rest_framework.routers import DefaultRouter
from . import views
router = DefaultRouter()
router.register(r'posts', views.PostViewSet, basename='post')
urlpatterns = router.urls
# Generated URLs:
# GET/POST /api/posts/ -> list / create
# GET /api/posts/my/ -> custom action
# GET/PUT/PATCH/DELETE /api/posts/{pk}/ -> detail operations
# mysite/settings.py — DRF default settings
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,
}
Related Resources
Django Reference
Complete tag & property list
Django How-To Guides
Step-by-step practical guides
Django Exercises
Practice what you've learned
More in Django