Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access request object within a custom Serializer Field in the Django REST framework?

Consider:

class CustomSerializerField(serializers.Field):

    def to_representation(self, obj):
       return obj

    def to_internal_value(self, data):
       # How can I access the request object here?
       return {}

And now the ModelSerializer

class SomeModelSerializer(serializers.ModelSerializer):
   some_field = CustomerSerializerField()

   class Meta:
       model = SomeModel
       fields = ('__all__', )

I have tried

self.request.user
like image 957
Dap Avatar asked Sep 19 '25 18:09

Dap


1 Answers

DRF is passing the outer contexts to nested levels during the execution. In your case, the SomeModelSerializer class passes all the context it took (from the view, probably) to its fields and "nested serializers"

To access the request variable in CustomerSerializerField, just use,

user = self.context['request'].user
.
like image 107
JPG Avatar answered Sep 23 '25 05:09

JPG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!