11👍
✅
In your view:
from django.core import serializers
json_serializer = serializers.get_serializer("json")()
companies = json_serializer.serialize(Company.objects.all().order_by('id')[:5], ensure_ascii=False)
In template:
var companies = '{{ companies|escapejs }}';
This is only for getting your data models into JS. For manipulating them, you should create some views that will get called from JS (by AJAX). They should probably return JSON. Check out
https://dev.to/brian101co/how-to-return-a-json-response-in-django-gen or https://simpleisbetterthancomplex.com/tutorial/2016/07/27/how-to-return-json-encoded-response.html on how to simply return only JSON from a view.
1👍
You must serialize your companies model data to json, so javascript will be able to read it.
So you’ll need to have two model variables, companies (the one you have right now) and companies_json which will hold the serialized data.
from django.core import serializers
companies_json = serializers.serialize("json", Company.objects.all())
I haven’t tested this.
- [Django]-Django: need help with keeping apps from depending on one another
- [Django]-In Django templates, `Context` is a stack. What for?
- [Django]-Force reload on client's webpage Django
- [Django]-Web Dev. Framework for RAD Web App Dev. in Shortest Time ( Yii vs. Django )
- [Django]-Keep User and Group in same section in Django admin panel
Source:stackexchange.com