0

I am beginner to django. I just want to post and register user. If I do that, I got error "CSRF Failed: CSRF token missing or incorrect." My apiview is like this.

class RegistrationView(APIView):
    """ Allow registration of new users. """
    permission_classes = (permissions.AllowAny,)

    def post(self, request):
        serializer = RegistrationSerializer(data=request.DATA)
        # Check format and unique constraint
        if not serializer.is_valid():
            return Response(serializer.errors,\
                            status=status.HTTP_400_BAD_REQUEST)
        data = serializer.data

        # u = User.objects.create_user(username=data['username'],
        #                              email=data['email'],
        #                              password='password')

        u = User.objects.create(username=data['username'])
        u.set_password(data['password'])
        u.save()

        # Create OAuth2 client
        name = u.username
        client = Client(user=u, name=name, url='' + name,\
                client_id=name, client_secret='', client_type=1)
        client.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)

I have read through about CSRF token.

How to make a POST simple JSON using Django REST Framework? CSRF token missing or incorrect

In my setting.py, it is like this. Do I need to change in global level? or where shall I modify so that I won't have CSRF token error when I register new user?

REST_FRAMEWORK = {

    'DEFAULT_AUTHENTICATION_CLASSES':
        ('rest_framework.authentication.OAuth2Authentication',
         'rest_framework.authentication.SessionAuthentication'),

    'DEFAULT_MODEL_SERIALIZER_CLASS':
        'rest_framework.serializers.ModelSerializer',

    'DEFAULT_PERMISSION_CLASSES':
    ('rest_framework.permissions.IsAdminUser',)
}
Community
  • 1
  • 1
Khant Thu Linn
  • 5,905
  • 7
  • 52
  • 120

1 Answers1

0

If you are using SessionAuthentication in Django REST framework then you need to supply the CSRF token in your POST. Take a look at this link Working with AJAX, CSRF & CORS.

Also take a look at the example javascript from the Django docs.

Jody Boucher
  • 331
  • 1
  • 7