Skip to content
Advertisement

Django REST authentication not working with React

actually I want: if a user is authenticated: then create/get the Cart with user, else: create/get the Cart with session key. But at first problem happened with authentication.

At first I tried to register the user and saved the key(got from drf) in local storage.

in Reactjs:

JavaScript

I think no problem here. if I console.log() the key , it prints the key successfully.

now look at my views.py . I think the problem is here.

JavaScript

now i made a button and if i click, this function call

reactjs:

JavaScript

So my question is:

*why it shows Forbidden if I comment out the line @permission_classes((IsAuthenticated,)) though i don’t want this line. because I also want, user can add item with session.

*(in views.py) when i print request.user it shows >>>AnonymousUser. how to print the real user?

  • Finally, How can I add an item to the Cart with an Authenticated user?

Advertisement

Answer

You need to add either DEFAULT_AUTHENTICATION_CLASSES in settings.py or add a decorator @authentication_classes([TokenAuthentication]) to the api_view if not done already.
Since you need the API to also be accessible to unauthenticated users, @permission_classes is not required.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement