Hello!
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 https://docs.djangoproject.com/en/3.0/topics/class-based-views/generic-display/.
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:
https://adamj.eu/tech/2020/02/18/safely-including-data-for-javascript-in-a-django-template/
See also Aymeric Augustin’s posts on django and react: https://fractalideas.com/blog/
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': serializer.data, 'context': context}
return Response(response_list)
def get_total_items_in_stock(self):
product_list = Product.objects.all()
total=0
for product in product_list:
total+=product.available_quantity
return total
That way, the context info can be retrieved at some reducer as:
total_items_in_stock: action.response.data.context.total_items_in_stock
Naturally, it’ll have to be mapped into a prop further on.
References:
http://www.cdrf.co/3.9/rest_framework.generics/RetrieveAPIView.html
https://www.django-rest-framework.org/api-guide/generic-views