Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
148
rated 0 times [  152] [ 4]  / answers: 1 / hits: 16941  / 12 Years ago, fri, april 27, 2012, 12:00:00

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_companies$', 'companies.views.all_companies')


the view:



def all_companies(request): 
companies = Company.objects.all().order_by('id')[:5];
return direct_to_template(request, 'all_companies.html', {'companies': companies} );


the html:



{% block sidebar %}
<div id=sidebar>
<!-- like google maps, short list of company info -->
<ul>
{% for comp in companies %}
<li>{{ comp }}</li>
{% endfor %}
</ul>
</div>
{% endblock %}


the js:



var tmp = {{ companies }}

More From » python

 Answers
2

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.


[#85922] Thursday, April 26, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dantel

Total Points: 7
Total Questions: 102
Total Answers: 97

Location: Saint Lucia
Member since Sat, Jun 6, 2020
4 Years ago
;