KEMBAR78
DRF CheatSheet | PDF | Computer Programming | Computing
0% found this document useful (0 votes)
52 views4 pages

DRF CheatSheet

The document is a cheat sheet for Django REST Framework (DRF) covering key concepts such as Generic API Views, Serializers, Permissions, Token Authentication, and handling migration errors. It includes examples of class-based views, serializer validation, custom permissions, and best practices for exam preparation. Additionally, it provides sample URL patterns for API endpoints.

Uploaded by

vamsi krishna
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views4 pages

DRF CheatSheet

The document is a cheat sheet for Django REST Framework (DRF) covering key concepts such as Generic API Views, Serializers, Permissions, Token Authentication, and handling migration errors. It includes examples of class-based views, serializer validation, custom permissions, and best practices for exam preparation. Additionally, it provides sample URL patterns for API endpoints.

Uploaded by

vamsi krishna
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Django REST Framework (DRF) Exam Cheat Sheet

1. Generic API Views (CBV - Class Based Views)

---------------------------------------------

- ListAPIView: GET (List all)

- RetrieveAPIView: GET (Single object)

- CreateAPIView: POST

- UpdateAPIView: PUT/PATCH

- DestroyAPIView: DELETE

- ListCreateAPIView: GET + POST

- RetrieveUpdateDestroyAPIView: GET + PUT/PATCH + DELETE

Example:

class GadgetListCreate(generics.ListCreateAPIView):

queryset = GadgetModel.objects.all()

serializer_class = GadgetSerializer

2. Serializers (Validation + Serialization)

---------------------------------------------

- CharField: serializers.CharField(error_messages={'required': 'This field is required'})

- IntegerField: serializers.IntegerField()

- Read-only: read_only_fields = ['author']

- Full Validation:

def validate_price(self, value):

if value <= 0:
raise serializers.ValidationError("Price must be positive")

return value

def validate(self, data):

if data['price'] > 100000:

raise serializers.ValidationError("Price too high!")

return data

3. Saving Current User as Author

---------------------------------------------

def perform_create(self, serializer):

serializer.save(author=self.request.user)

4. Permissions

---------------------------------------------

Built-in: IsAuthenticated, IsAdminUser, AllowAny

Custom Permission Example (Only author can update/delete):

from rest_framework.permissions import BasePermission

class IsAuthorForPatchAndDelete(BasePermission):

def has_object_permission(self, request, view, obj):

if request.method in ['PATCH', 'DELETE']:

return obj.author == request.user

return True

Apply Permission:
permission_classes = [IsAuthenticated, IsAuthorForPatchAndDelete]

5. Token Authentication (JWT or DRF Token)

---------------------------------------------

- Login to get token

- Send token in Authorization header

REST_FRAMEWORK = {

'DEFAULT_AUTHENTICATION_CLASSES': (

'rest_framework_simplejwt.authentication.JWTAuthentication',

),

'DEFAULT_PERMISSION_CLASSES': (

'rest_framework.permissions.IsAuthenticated',

),

6. Overriding Status Codes

---------------------------------------------

from rest_framework.response import Response

from rest_framework import status

def create(self, request, *args, **kwargs):

response = super().create(request, *args, **kwargs)

return Response({'message': 'Created Successfully!'}, status=status.HTTP_201_CREATED)

7. Migration Errors + Fixes


---------------------------------------------

- Table already exists: python manage.py migrate --fake-initial

- Stuck migration: python manage.py migrate appname zero --fake then migrate again

- OperationalError: Check db and migration state

8. Best Practices for Exam

---------------------------------------------

- Always set author=self.request.user

- Use permission_classes

- Validate in Serializer

- Know at least 1 custom permission

- Know Token Authentication flow

- Be ready for custom status codes

- Know difference between APIView types

- Know migration error fixes

Bonus URLs Example:

from django.urls import path

from .views import GadgetListCreate, GadgetUpdateDetail

urlpatterns = [

path('gadgets/', GadgetListCreate.as_view()),

path('gadgets/<int:pk>/', GadgetUpdateDetail.as_view()),

You might also like