Skip to content
Advertisement

Django Rest Frame Work: passing User in djago rest frame work

I have a Django project as following code in model

JavaScript

following code in serializer

JavaScript

and following code in view

JavaScript

when I send a post request by postman and send username and password in Authorization tab it error:

JavaScript

but if I type username or password incorrect it will be

JavaScript

can everybody help me?

Advertisement

Answer

Your serializer has no idea about the currently logged-in user.You to pass it as context from request. user or request.

I personally prefer CurrentUserDefault to be used in the serializer. To make it work we need to pass the request as context because CurrentUserDefault picks user from context request. We need to update our views and serializer code as follows

Views file: Add request as context context

JavaScript

serializer.py: Update your serializer to auto-populate created_by_user

JavaScript

It will solve your user field required issue.

JavaScript

Now coming to your next part of the issue that is related to incorrect passwords.

By default, APIView picks the default authentication class from settings. Inside projects settings.py, we mostly write these lines while using DRF and they serve as default authentication for APIView:

From settings.py

JavaScript

Inside APIView you can have a look at default permission_classes, and authentication_classes

From inside APIView:

JavaScript

that is when you type an invalid password:

JavaScript

Provide the correct username and password to your APIView from postman so that it gets the requested logged-in user for auto-populates at DB level.

Advertisement