最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - is it possible to use javascript to get data from django models db? - Stack Overflow

programmeradmin4浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 11

In 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.

发布评论

评论列表(0)

  1. 暂无评论