Session Auth in Django-Rest-Framwork, Is this really what I have to do to make is CSRF safe?

First off, this code works, it just doesn't feel as clean as it should be for something so simple.

Background: I'm trying to make a custom login API endpoint in DRF that will be consumed by the React Frontend. It seems you have to manually force a csrf to be sent in DRF so that's what I have done.

I didn't want to send over a Django Form because it didn't seem RESTful, but this is the only method I could find to avoid that. Please let me know if this is clean code.

from rest_framework import serializers
from django.contrib.auth import get_user_model # If used custom user model

UserModel = get_user_model()

class UserSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True)
    def create(self, validated_data):
        user = UserModel.objects.create_user(

        return user

    class Meta:
        model = UserModel
        # Tuple of serialized model fields (see link [2])
        fields = ( "id", "username", 'email', "password", )

from rest_framework import permissions

from django.contrib.auth import get_user_model # If used custom user model
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status

from .serializers import UserSerializer

from django.utils.decorators import method_decorator
from django.views.decorators.csrf import ensure_csrf_cookie, csrf_protect

class CreateUserView(APIView):
    model = get_user_model()
    permission_classes = [
        permissions.AllowAny # Or anon users can't register
    serializer_class = UserSerializer

    def get(self, request, format = None):
        return Response(status=status.HTTP_200_OK)

    def post(self,request, format = None):
        serializer = UserSerializer(
        if serializer.is_valid():
            return Response(, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Read more here:

Content Attribution

This content was originally published by Joseph Gutstadt at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: