I’m very new to web development and I know this might be stupid approach but cannot think of a better way of doing this. In the views.py a method returns a dictionary named sniffer_aps to the template in following format:
sniffer_aps = {device1:[ap1, ap2], device2:[ap3, ap4, ap5], ......}
In the template I have a dropdown list that lists all devices(device1, device2, ……).
In another field I list all aps belong to the device selected in the dropdown list. I want to dynamically adjust the field according to the device I selected, but it doesn’t really work.
The dropdown list code is:
<select onchange="refresh(this.value)" id="sniffer_list">
{% for sniffer_ap in sniffer_aps %}
<option value={{ sniffer_ap }}>{{ sniffer_ap.plug_ip }}</option>
{% endfor %}
</select>
My question is that how can I loop though the value in the field that shows aps based on the option selected in the dropdown list?
Right now my approach is to use javascript to detect the “onchange” event of the dropdown list, and change the value the field that list all aps accordingly, then just get the value of the field and treat it as the key of the dictionary.
function refresh(key) {
$('.router').attr('value') = key;
}
For the field that lists aps, it is where the problem is. I’m trying to achieve something like this:
<select multiple="multiple" size="6">
{% for router in sniffer_aps[this.value] %}
<option class="router" value="">{{ router }}</option>
{% endfor %}
</select>
Please correct my approach, or if somebody can provide a better way. Thanks very much.
You’re running into trouble here because you’re confusing server-side code (Django’s templating engine) with client-side code (the Javascript code you’re using for the
onchangehandler). Your server-side code will have run on the server before the resulting HTML is ever delivered to the client, so you can’t have any interactions between client-side Javascript and the template logic.You’re right to use Javascript and the
onchangeevent to update the values in the field that lists apps – you could do this on the server, by submitting the form and changing the HTML with Django when the new request is returned, but this takes a new webpage load and isn’t nearly as fast or user-friendly as doing it with Javascript.I would approach this by:
Converting the dictionary to JSON in your Django view class:
Outputing the JSON as a JavaScript object in your template code:
Using JavaScript to update the apps field, using this data. There are many questions addressing this on StackOverflow – you might consider using jQuery, as it makes this sort of manipulation much easier.