Reputation: 147
I'm pretty new to Django and web development in general so I'm still trying to conceptualize a lot of these ideas.
What I'm having a hard time understanding is how to properly handle an HTML form action attribute upon clicking a "submit" button, based on what was chosen in select/dropdown boxes I have set up.
For example, If a user were to select a car (or trim in my example below) in a dropdown box, then clicked the go button, I would want to then send the user to a new page with information about the car trim. Here is what I have:
Template
<!-- Bar of dropdowns for searching. -->
<div class="container-fluid">
<form action="" method="get" class="form-inline" id="dropdownText">
<div class="form-group" id="dropdownGroup">
<span style="display:inline-block" class="selectBox">
<select class="form-control" id="make">
<option value='empty'></option>
<!-- List each make's name. -->
{% for make in allMakes %}
<option value="{{ make.id }}">{{ make.name }}</option>
{% endfor %}
</select>
<label for="make" style="display:block">Make</label>
</span>
<span style="display:inline-block" class="selectBox">
<select class="form-control" id="model" disabled>
<!-- List each make's model's name. -->
</select>
<label for="model" style="display:block">Model</label>
</span>
<span style="display:inline-block" class="selectBox">
<select class="form-control" id="trim" disabled>
<!-- List all trims for each make/model. -->
</select>
<label for="trim" style="display:block">Trim</label>
</span>
</div>
</form>
<form action="" id="trimDetail">
<div class="text-center">
<button type="submit" class="btn btn-default" id="go">GO!</button>
</div>
</form>
</div>
What it looks like
http://puu.sh/phaHG/105ed07b28.png
DetailView for the car trim
class DetailView(generic.DetailView):
model = Trim
template_name = 'search/detail.html'
URL that will correspond to the view
url(r'^(?P<pk>\d+)/$', DetailView.as_view(model=Trim,
template_name='search/detail.html')),
Upon selecting the trim and clicking go, the page is simply refreshed with the url changing to:
"/?trimId=4"
, the trimId changing based on what the user selected, but not sending them to the template that will display the information for the id.
I can make this work by simply changing the form action using jQuery upon clicking the button, but i wasn't sure if this was bad practice, and I want to learn the proper Django way of doing it.
My jQuery way of doing it:
var $elTrim = $('select#trim'); // The trim select box.
var $trimForm = $('form#trimDetail'); // The form around the button.
function updateAction(){
if($elTrim.find('option:selected').val() != 'empty'){
$trimForm.attr('action', $elTrim.val());
}
}
$elTrim.change(updateAction);
Upvotes: 0
Views: 894
Reputation: 599520
This isn't a good way of doing it. Your search page should always submit to the same place; that page can then be responsible for either showing the results directly, or redirecting you to the relevant page that does.
Upvotes: 1