django and ajax dropdown based on selected dropdown
You are using values
method in your QuerySet and only sending swtype
field value in context while rendering project_dropdown_options.html
Either remove the values
method
result = SWTypes.objects.filter(proje=int(id))
Or add pk
as well to values
result = SWTypes.objects.filter(proje=int(id)).values('pk', 'swtype')
Also, you don't have to convert
QuerySet
tolist
, you can loop over Queryset as well in the template
<option value="">---------</option>{% for sw in result %} <option value="{{ sw.pk }}">{{ sw.swtype }}</option>{% endfor %}
UPDATE
Change your parent HTML as well, replace name
attribute of select tag with id
, as you have attached JQuery change event on id
i.e $("#projects").change
<td> <!-- add id in place of name --> <select id="projects"> {% for instance in projects%} <option value={{ instance.id }}>{{ instance.project_title }}</option> {% endfor %} </select> </td> <td> <form method="post" id="personForm" projects-drop-url="{% url 'ajax_projects_dropdown' %}" novalidate> {% csrf_token %} <select name="sw" id="sw"> <option value="">Switch Type</option> </select> </form> </td>
UPDATE 2
Change your ajax call, remove data
property and append id
to URL itself as a query parameter, and use document on
event
$(document).on('change', 'select#projects', function () { var url = $("#personForm").attr("projects-drop-url"); var id = $(this).val(); console.log("urls and project_id", url, id); $.ajax({ type: "GET", url: url + "?id="+ id, success: function (data) { $("#sw").html(data); } });});