How to modify the frontend context for a React App using GenericViews?


I’m trying to transmit additional context to the front end through a ListAPIView by rewriting get_context_data so it returns a modified context["text_var"]="123".

When I try to use something like <p>{{ test_var }}</p> at a index.js, I get the console error: “Uncaught ReferenceError: test_var is not defined”.

I’m trying to follow the patterns from

Maybe the fact that the frontend is a React application implies in the requirement of additional steps?
Can someone please point me what I’m missing here?

Kind regards

Context data isn’t immediately available in JavaScript, you have to pass it through.

See my post for an explanation of the safe way to do this:

See also Aymeric Augustin’s posts on django and react:

1 Like

Thank you for the reference and the quick reply. I’ll read it right away.

I’ve found how to do it, I’ll post the answer here for further reference. The key was to override the list method of the class ListAPIView.

class ListInventoryEndpoint(ListAPIView):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer

    def list(self, request, *args, **kwargs):
        serializer = self.get_serializer(self.get_queryset(), many=True)
        context = {'total_items_in_stock': self.get_total_items_in_stock()}
        response_list = {'load':, 'context': context}
        return Response(response_list)
    def get_total_items_in_stock(self):
        product_list = Product.objects.all()
        for product in product_list:
        return total

That way, the context info can be retrieved at some reducer as:


Naturally, it’ll have to be mapped into a prop further on.