简体   繁体   中英

Date filtering with Django -- how to send start and end dates to my view?

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 &#8595;</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.

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  name="date_filter">Submit</button>
</form>

There are basically three button types :

Button Types

There are three types of buttons:

  • submitSubmits the current form data . (This is default.)
  • reset — Resets data in the current form.
  • buttonJust a button . Its effects must be controlled by something else (that is, with JavaScript).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM