简体   繁体   中英

How do I send Django object as parameter in Javascript?

So as mention in title, I'm trying to send my Django object to JavaScript so I can massage it in the front end. Let me show you the code (simplified). views.py

def main_page(request):
    contents = Contents.objects.all()

    context = {
            'contents' : contents
        }

    return render(request, 'main/home.html', context)

template

    {% for u in all_ans_us_paginated %}
    <div class="row">
        <div class="col">
            <div class="" id="{{u.id}}" onclick="DetailModal('{{u}}')">
            </div>
        </div>
    </div>
    {% endfor %}

...

<script>
    function DetailModal(u) {
        console.log('{{u.author}}');
        console.log('{{u.body}}');
    }
</script>

My intention is to show a modal when the click event is triggered. But putting the modal part aside, I can't pass data as parameter to JavaScript.

*I don't want to make any changes in the python code. Is it possible to do it only with HTML and JavaScript?
** JSON.parse(u) won't work, because u is string.

IN DJANGO

from django.shortcuts import render
from json import dumps
def send_dictionary(request):
# create data dictionary
dataDictionary = {
    'hello': 'World',
    'geeks': 'forgeeks',
    'ABC': 123,
    456: 'abc',
    14000605: 1,
    'list': ['geeks', 4, 'geeks'],
    'dictionary': {'you': 'can', 'send': 'anything', 3: 1}
}
# dump data
dataJSON = dumps(dataDictionary)
return render(request, 'main / app.js', {'data': dataJSON})

IN JAVASCRIPT

app.js file :

var data = JSON.parse("{{data|escapejs}}");
for(var x in data){
 // Write What You Want Here
}

if you want a clean view of the code use this way because javaScript considers dictionaries as separate objects

  dataDictionary = [
    ["Laugh", "Cry"],
    ["Even", "Odd"],
    ["Hot", "Cold"],
    ["Light", "Dark"],
    ["Opposite", "Same"],
    ["Far", "Near"],
    ["Give", "Take"],
    ["Night", "Day"],
    ["Import", "Export"],
    ["Hard", "Easy"],
    ["Never", "Always"],
    ["Late", "Early"],
    ["Less", "More"],
    ["Male", "Female"],
    ["Happiness", "Sadness"],
    ["Fast", "Slow"],
    ["Old", "Young"],
    ["Boy", "Girl"],
    ["Up", "Down"],
    ["Left", "Right"],
    ["Rich", "Poor"],
    ["Love", "Hate"],
    ["Inside", "Outside"],
    ["Bad", "Good"],
    ["Short", "Tall"],
   ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM