Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't get request data

I have a viewset and a function with an additional address (decorator @action). In the serializer, I define an additional field through the SerializerMethodFieldenter image description here, and in order to define it, I need to know the user data through request.user. So the problem is, when the request goes through the viewset address (…/api/users/), everything is fine, but when it go through my additional address (…/api/users/subscriptions) there is no request data and i get this user = self.context.get(‘request’).user
AttributeError: ‘NoneType’ object has no attribute ‘user’

The serializer has no information about the request that went through @action

viewset url

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@action url, self.context is empty

>Solution :

Simple way using your code, just change in UserViewSet to:

.....
context = {
    'request': self.request,
    'format': self.format_kwarg,
    'view': self
}
serializer = UserSerializer(users, many=True, context=context)
.....    

Check https://www.cdrf.co/3.14/rest_framework.viewsets/ModelViewSet.html method: get_serializer_context

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading