Search code examples
djangovue.jsdjango-rest-frameworkdjango-authentication

Accessing User ID from window.LocalStorage


I have a DjangoRestFramework / Vue.js application. For now I was getting my logged user with this.requestUser = window.localStorage.getItem("username"); I just needed my requestUser to check if a user was logged or not. Now I have to "POST" data via an endpoint, but in my backend, DRF is expecting an ID not a string value. So I checked my window.localStorage with the 'developer tool' and only my username value is stored, not its value.

I have few options:

-create a new endpoint that will fetch an user ID from its value. And then on created() run a function that will save it into window.localStorage

-modify my models and serializers so I can use my user value instead of its ID to interact with my endpoints.

-or simply there is a configuration that I am not aware of than can save my user.id as well as my user.username

In DRF I am using plain django.contrib.auth for my User model. What is the best approach for my problem?


Solution

  • As you are using authentication, then you can get the id from request.user.id in the backend.

    request.user typically returns an instance of django.contrib.auth.models.User

    Reference