简体   繁体   中英

Django-Calling python script in HTML

I have a python script written up that returns a list of values from a database. I want to incorporate that script into my django website that I have created. I have an html file right now in my templates folder that has dictionary values hardcoded but how do I replace the dictionary hardcoded material with the script, lets call it values.py

<script type="text/javascript">
$(document).ready(function() {
    var dropDown = [" ", "Run1", "Run2", "Trail1", "Trail2"];
    var dropDownID = [" ", "111111", "222222", "333333", "444444", "555555"];
    $("#dropDown").select2({
        data: dropDown
    });

    $("#dropDown").change(function() {
        $("#dropdownID").val(dropDownID[$("#dropDown option:selected").index()]);
    });
});

Now do I just add my values.py into my templatetag folder and then from there do I just fill the var dropDown = [" ", "Run1", "Run2", "Trail1", "Trail2"]; to something like

var dropDown = [
    {% load tag %}
    <div id="id_div">
        {% value %}
    </div>
]

Create a view to generate this data:

# views.py
import json

def getdropdown(request)
    mydata = ...
    return http.HttpResponse(
        json.dumps(mydata),
        mimetype='application/javascript'
    )

javascript:

$(document).ready(function() {
    var dropDown = [];
    // ...
    $.getJSON("<url of the getdropdown view>", function(data){
      dropDown = data;  
    })
    // ... r async call
})

可以这样做:

var dropDown = {{dropDown|safe}};

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