0

I would like to create a GET endpoint that returns the JSONResponse of the current logged-in user. Ideally, it would look like:

{
    "username": "joe",
    "email": "[email protected]",
    "first_name": "",
    "last_name": "",
    "last_login": "2021-09-17T17:11:00.039Z",
    "is_superuser": true,
    "is_active": true
}

(Note that I'm using Django 3.2, not Django REST API)

This requires serializing the current user object, but serializing a single object is... opaque in the documentation, and many similar questions have responses from 6 or more years/two major versions ago.

1 Answer 1

1

I've solved this problem by re-querying the user from the request.user object and singling out the first field. This has the added benefit of controlling the fields. Note that I've already tested to make sure the user is logged in at this point.

def api_current_user(request: HttpRequest):
    user = (
        User.objects.filter(pk=request.user.pk)
        .values(
            "username",
            "email",
            "first_name",
            "last_name",
            "last_login",
            "is_superuser",
            "is_active",
        )
        .first()
    )
    return JsonResponse(user)
1
  • 1
    You are a life saver. Damn I have been searching for about two hours now just seeing irrelevant stuff like serializing. I was just about getting frustrated. Thank you very much for this. Apr 28 at 19:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.