Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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 }}
share|improve this question

2 Answers 2

up vote 2 down vote accepted

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 http://djangosnippets.org/snippets/622/ or http://djangosnippets.org/snippets/2102/ on how to simply return only JSON from a view.

share|improve this answer
    
thanks for the info, now how do i call the views from js? –  yao jiang Apr 28 '12 at 15:16
    
if you use jQuery: api.jquery.com/jQuery.getJSON –  frnhr Apr 29 '12 at 12:23

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.