My application has a /login
endpoint where users can enter their login information, and after a user has been authenticated I would like to display a DRF view based on it's user ID as a parameter in the URL. What is the best way to do that ? Shall I need to include the user ID into the HTTP response and if so, how to do that ?
This is how the login view and serializer look like :
view.py
class LogInView(TokenObtainPairView):
serializer_class = LogInSerializer
serializer.py
class LogInSerializer(TokenObtainPairSerializer):
@classmethod
def get_token(cls, user):
token = super().get_token(user)
user_data = ManagerSerializer(user).data
for key, value in user_data.items():
if key != 'id':
token[key] = value
return token
The view I would like to display after the user login looks like this :
view.py
class AccountDetails(RetrieveAPIView):
serializer_class = AccountSerializer
queryset = Account.objects.all()
urls.py
router = routers.DefaultRouter()
urlpatterns = [
path('', include(router.urls)),
path('account/<pk>', AccountDetails.as_view()),
]
CodePudding user response:
Why you need User ID? You can query it yourself from request.user. You just need to override the RetrieveApiView's get_object method:
class AccountDetails(RetrieveAPIView):
serializer_class = AccountSerializer
queryset = Account.objects.all()
def get_object(self):
return request.user