Reputation: 510
I'm trying to add date filtering to an event listing I have on my Django site. In other words, I want the user to be able to select start and end dates and then show all events on or between those dates.
I've tried the below code, which I feel like should be working.
relevant HTML
<div id="datefilter-container">
<p class="js-command">Filter shows by date ↓</p>
<div id="datefilter">
<form name="date-range-form" id="date-range-form"
action="{% url 'concerts:date_filter' %}" method="GET">
<label for="start">Start date:</label>
<input type="date" id="start" name="start">
<label for="end">End date:</label>
<input type="date" id="end" name="end">
<button type="button" name="date_filter">Submit</button>
</form>
</div>
</div>
urls.py (relevant line)
url(r'^date_filter/$', views.filter_by_date, name="date_filter"),
views.py (relevant function)
def filter_by_date(request):
if request.method == "GET":
start_date = request.GET.get('start')
end_date = request.GET.get('end')
try:
results = Concert.objects.filter(
Q(date__gte=start_date) & Q(date__lte=end_date)
)
except Concert.DoesNotExist:
results = None
template = "concerts/calendar.html"
context = {
"results" : results,
"start_date" : start_date,
"end_date" : end_date
}
return render(request, template, context)
else:
return render(request, "concerts/calendar.html", {})
Nothing is happening when I press the submit button in my HTML. I'm not sure if this is a problem with my HTML or my view. A little guidance would be greatly appreciated.
Upvotes: 2
Views: 1484
Reputation: 477318
Nothing is happening when I press the submit button in my HTML.
That is because you did not specify that the browser should submit the query when you click on it. You can specify that by setting the type=...
to "submit"
:
<form name="date-range-form" id="date-range-form" action="{% url 'concerts:date_filter' %}" method="GET">
<!-- ... -->
<button type="submit" name="date_filter">Submit</button>
</form>
There are basically three button types:
Button Types
There are three types of buttons:
submit
— Submits the current form data. (This is default.)reset
— Resets data in the current form.button
— Just a button. Its effects must be controlled by something else (that is, with JavaScript).
Upvotes: 2