[Fixed]-Django REST Framework – CurrentUserDefault use


Django REST Framework handles the serialization and deserialization of objects using a central serializer. In order to help deserialize and serialize sometimes, it needs a bit of context like the current view or request that is being used. You typically don’t have to worry about it because the generic views handle it automatically for you. This is covered in the documentation under “Including extra context” and it takes advantage of the optional context parameter for serializers.

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

context = {
    "request": self.request,

serializer = NewModelSerializer(data=request.data, context=context)

The context dictionary is also available on generic views as the get_serializer_context method, which will automatically populate the dictionary with commonly used keys such as the request and view.

Leave a comment