I am trying to do something very simple but haven’t found how to do it yet.
I have a model and an endpoint returning a JSON array reprenseting the instances of this model with Django Rest Framework. I want to include the JSON in an HTML template (for SEO and for fast initial data loading). Something like
<script>
var data = {% json_from_django_rest_framework "mymodel" %};
</script>
Is there an easy way to do this? Should I just go a different way?
2
Answers
As discussed in the comments, here is an example of how to reuse the result from your api endpoint in a normal Django view by using Django’s
resolve
function.views.py
my-template.html
Note 1: Instead of hardcoding the path in
rev = '/path/to/api/endpoint/'
it is better toreverse()
the url, but I left it out to remove that as a source for errors. If you are going this direction, here is a list of the default url names provided by DRFNote 2: The snippet would benefit from exception handling, like making sure that
res
returned 200, has thedata
property, etc.Another way of doing this, which gets around rendering the view.
In your views.py;
And in your template;
It should really go without saying that you should pay attention to potential performance issues with this approach, ie.. perhaps it’s best to paginate
bars
.