1

I am new to django rest framework, and trying to write a view to register users but whenever i am running my view by hitting the desired url i get the following error.

Error:-

Forbidden (403)
CSRF verification failed. Request aborted.

You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties.

If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for “same-origin” requests.

View:-

class UserRegistration(mixins.CreateModelMixin, generics.GenericAPIView):
    serializer_class = RegistrationSerializer

    def post(self, request, *args, **kwargs):
        return super().create(request, *args, **kwargs)

Serializer:-

class RegistrationSerializer(serializers.ModelSerializer):
    password2 = serializers.CharField(style={'input_type': 'password'}, write_only=True)

    class Meta:
        model = User
        fields = ['username', 'email', 'password', 'password2']
        extra_kwargs = {
            'password': {'write_only': True}
        }

    def save(self):
        password = self.validated_data['password']
        password2 = self.validated_data['password2']
        if password != password2:
            raise serializers.ValidationError({'error': 'p1 and p2 must be same'})

        if User.objects.filter(email=self.validated_data['email']).exists():
            raise serializers.ValidationError({'error': 'email already exists'})

        account = User(email=self.validated_data['email'], username=self.validated_data['username'])
        account.set_password(password)
        account.save()
        return account

Note:- I am using postman forAPI testing. I know there are some great way to do the same, but for this instant i would like make this code up and running.

Thanks in advance.. Hope to here from you soon..

Atharva
  • 87
  • 1
  • 9
  • Does this answer your question? [Run django api from postman: CSRF verification failed](https://stackoverflow.com/questions/46926227/run-django-api-from-postman-csrf-verification-failed) – Abdul Aziz Barkat Sep 03 '21 at 04:06

1 Answers1

1

You can make your code work by not validating csrf. So, you can use csrf_exempt :

from django.utils.decorators import method_decorator

@method_decorator(csrf_exempt, name='dispatch')
class UserRegistration(mixins.CreateModelMixin, generics.GenericAPIView):
    serializer_class = RegistrationSerializer

    def post(self, request, *args, **kwargs):
        return super().create(request, *args, **kwargs)

Refs: method_decorator

Biplove Lamichhane
  • 3,995
  • 4
  • 14
  • 30