I am trying to get the django model object to show on a html page. Of course when I tried to use {{ object }}, I get an error.
How do I properly get the django data model and manipulate the attributes using javascript?
the url:
('^all_panies$', 'panies.views.all_panies')
the view:
def all_panies(request):
panies = Company.objects.all().order_by('id')[:5];
return direct_to_template(request, 'all_panies.html', {'panies': panies} );
the html:
{% block sidebar %}
<div id="sidebar">
<!-- like google maps, short list of pany info -->
<ul>
{% for p in panies %}
<li>{{ p }}</li>
{% endfor %}
</ul>
</div>
{% endblock %}
the js:
var tmp = {{ panies }}
I am trying to get the django model object to show on a html page. Of course when I tried to use {{ object }}, I get an error.
How do I properly get the django data model and manipulate the attributes using javascript?
the url:
('^all_panies$', 'panies.views.all_panies')
the view:
def all_panies(request):
panies = Company.objects.all().order_by('id')[:5];
return direct_to_template(request, 'all_panies.html', {'panies': panies} );
the html:
{% block sidebar %}
<div id="sidebar">
<!-- like google maps, short list of pany info -->
<ul>
{% for p in panies %}
<li>{{ p }}</li>
{% endfor %}
</ul>
</div>
{% endblock %}
the js:
var tmp = {{ panies }}
Share
Improve this question
asked Apr 27, 2012 at 22:40
iCodeLikeImDrunkiCodeLikeImDrunk
17.8k36 gold badges116 silver badges174 bronze badges
2 Answers
Reset to default 11In your view:
from django.core import serializers
json_serializer = serializers.get_serializer("json")()
panies = json_serializer.serialize(Company.objects.all().order_by('id')[:5], ensure_ascii=False)
In template:
var panies = '{{ panies|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://simpleisbetterthanplex./tutorial/2016/07/27/how-to-return-json-encoded-response.html on how to simply return only JSON from a view.
You must serialize your panies model data to json, so javascript will be able to read it.
So you'll need to have two model variables, panies (the one you have right now) and panies_json which will hold the serialized data.
from django.core import serializers
panies_json = serializers.serialize("json", Company.objects.all())
I haven't tested this.