简体   繁体   中英

Injecting js variable in django url

My url looks like this:

path('tree_sensor\/(?P<sensorID>.*)', views.tree_sensor, name='tree_sensor')

and i have a var sID = 1,2,etc which i want to inject into a django url in a button

<a class='popup_button small_text' href='{% url 'agriculture:tree_sensor' "sID" %}'><span>Sensor Page</span></a>")

template:


for (i in motePos) {
    markers.addLayer(mote[i].on('click', function(e) {
        var sID = this.id;
       
        $.ajax({
            type : 'GET',
            url : "{% url 'agriculture:sensor_ms' %}",
            data : {"sID" : sID},
            success: function(response){
               
                var measurement = JSON.parse(response["measurement"]);
                var fields = measurement[0]["fields"];
                console.log(sID)
                mote[i].bindPopup("<h3>Tree Sensor: " + motePosName[i] + "</h3>" 
               "<br><a class='popup_button small_text' href='{% url 'agriculture:tree_sensor' sID %}'><span>Sensor Page</span></a>").openPopup();
                mote[i].name = motePosName[i];
                mote[i].id = motePosId[i];     
            }
        })
    }));

Current url prints "tree_sensor/sID". I want to get the ID from the objects so it would be something like "tree_sensor/1" "tree_sensor/2" etc.

As DrummerMann suggested it works out like this:

var sensorID = "href='{% url 'agriculture:tree_sensor' 12345 %}'";
var url_mask = sensorID.replace("12345", fields["sensor"]);

and the button to the link

"<br><a class='popup_button small_text' "+url_mask+" ><span>Sensor Page</span></a>"

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