In Django, how do I pass the selected dropdown value from a template to view?

I've been looking for a solution for this for so long, but still can't find it. I have a large form in my template, which actually consists of a bunch of model forms. One field in this large form is not part of the form, but represents one dynamic drop-down menu that is populated from a table called "Institutions" in views.py as such: Institutions.objects.all ()

Here is the part from views.py:

def submission_form(request): institutions = Institution.objects.all() if request.method == 'POST': abstractform = AbstractForm(request.POST) authorform = AuthorForm(request.POST) # Here I want code: if selected institution is this, then do that if abstractform.is_valid() and authorform.is_valid() new_abstract = abstractform.save() new_author = authorform.save() else: return render(request, 'records/submission_form.html', {'abstractform': abstractform, 'authorform': authorform, 'institutions':institutions }) 

This is revealed in my template:

  <select id="ddlInstititions"> <option value="%">---------</option> {% for entry in institutions %} <option value="{{ entry.id }}">{{ entry.name }}</option> {% endfor %} </select> 

My question is: is it possible to pass the selected name entry.name to the view so that I can use it there? If not, what do you recommend doing instead?

Any help would be greatly appreciated!

+7
django
source share
2 answers

For any form element to be submitted in POST, you need to have a name attribute. Therefore, it should be <select id="ddlInstititions" name="institutions"> .

What is passed in the view to POST is the value attribute of each option element. You have currently set this to entry.id , so this is the identifier that will be in POST. You can use this to search for the Institution object and get the name, or you can change the form so that you put entry.name directly in the value attribute.

+9
source share

You can use jQuery $ .ajax () for this.

In your Javascript, you can bind an event handler to #ddlInstititions via

 $("#ddlInstitions").on("change", function(){ var selectedValue = $(this).text(); $.ajax({ url : "insititionsSelectHandler/", type : "GET", data : {"name" : selectedValue}, dataType : "json", success : function(){ } }); }); 

What this will do when you do the select event in the dropdown list, it lights up with this event handler. You will need to define this url in your `urls.py ', e.g.

 (r'^/institionsSelectHandler/$', views.insititionsSelectHandler), 

and you can get the value inside the presentation method, for example

 def insititionsSelectHandler(request): key = request.GET["name"] ... ... ... #and return your results as a HttpResponse object that contains a dict return HttpResponse(simplejson.dumps({"success" : "true", "message" : ... }, mimetype = "application/json") 
+5
source share

All Articles