Django REST Framework - using CurrentUserDefault

I am trying to use the CurrentUserDefault class for a single serializer.

 user = serializers.HiddenField(default=serializers.CurrentUserDefault()) 

The docs say:

To use this, a β€œquery” must be provided as part of the context dictionary when instantiating the serializer.

I am not sure how to create a serializer. In the view, I create all serializers with:

 serializer = NewModelSerializer(data=request.data) 

So I tried:

 context = dict(request.data) context['request'] = request serializer = NewModelSerializer(data=context) 

and

 context['request'] = {'user': request.user} 

And in both cases the error is the same:

 Exception Type: KeyError Exception Value: 'request' on: /Users/Alfonso/virtualenvs/sports/lib/python2.7/site-packages/rest_framework/fields.py in set_context self.user = serializer_field.context['request'].user 

Also I tried to execute unicode with dictionary keys ( u'request' ) with the same luck.

Is there a better way to pass registered user to serializer?

I am using Django REST Framework 3.0 and Python 2.7.6

+8
python django django-rest-framework
source share
1 answer

The Django REST Framework handles the serialization and deserialization of objects using a central serializer. To sometimes deserialize and serialize sometimes, it takes a little context, for example, the current view or request that is being used. You usually do not need to worry about this because general views process it automatically for you. This is described in the "Including Extra Context" documentation, and it uses an additional context parameter for serializers.

When you use serializers manually, the context should be passed as a dictionary. Some fields require specific keys, but for the most part, you only need the request key to reference the incoming request. This will allow HyperlinkedRelatedField generate the full URL, and additional functions like CurrentUserDefault will perform as expected.

 context = { "request": self.request, } serializer = NewModelSerializer(data=request.data, context=context) 

The context dictionary is also available in general views as the get_serializer_context method, which automatically populates the dictionary with commonly used keys, such as request and view .

+11
source share

All Articles