最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Get currenty logged in user in DjangoAngular - Stack Overflow

programmeradmin1浏览0评论

I am creating a Django / Angular project but I am having an issue. In normal django applications without frontend framework we can just do request.user and we can get the iformation needed. I already created the api endpoints to my User model but is there a way to directly find the user Id to make a call like this:

  getUserById(userId: number): Observable<User> {
    const url = `${this.baseUrl}users/${userId}/`;
    return this.http.get<User>(url);
  }

Or do I need to set up a different serializer like this for example:


class CurrentUserView(APIView):
    permission_classes = [IsAuthenticated] 

    def get(self, request):
        user = request.user  # Get the current logged-in user
        serializer = UserSerializer(user)
        return Response(serializer.data)

make a call to this endpoint and then with the data from here access the rest of the endpoints? Also right now I havent set up an Authentication mechanism. Maybe in the future if I do I wont be needing an endpoint like this? Thanks in advance

I am creating a Django / Angular project but I am having an issue. In normal django applications without frontend framework we can just do request.user and we can get the iformation needed. I already created the api endpoints to my User model but is there a way to directly find the user Id to make a call like this:

  getUserById(userId: number): Observable<User> {
    const url = `${this.baseUrl}users/${userId}/`;
    return this.http.get<User>(url);
  }

Or do I need to set up a different serializer like this for example:


class CurrentUserView(APIView):
    permission_classes = [IsAuthenticated] 

    def get(self, request):
        user = request.user  # Get the current logged-in user
        serializer = UserSerializer(user)
        return Response(serializer.data)

make a call to this endpoint and then with the data from here access the rest of the endpoints? Also right now I havent set up an Authentication mechanism. Maybe in the future if I do I wont be needing an endpoint like this? Thanks in advance

Share Improve this question asked Nov 20, 2024 at 11:00 0xDukis0xDukis 257 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 0

I guess you are using session authentication so in that case you have to append withCredentials: true option to every request.

Consider creating interceptor that does this to every request.

Example: Angular 4 - setting withCredentials on every request - cors cookie

Not setting up the authentication is the reason you are facing this problem. Please try to integrate django-rest-framework-simplejwt on django side. This token usually contains the user id and on frontend side you can save this token in localstorage to make the calls for rest of the endpionts.

发布评论

评论列表(0)

  1. 暂无评论