0

So I have a simple listview and override the queryset to include form fields for the user to search for specific available items.

To filter the list results, I'm using; request.method == 'GET', I know I can check if any field are empty and show all results or none.

I'm having trouble using the DateField(), When I'm not using the dateformat "YYYY/MM/DD", Django throws an ValidationError;

["'02/10/2019' value has an invalid date format. It must be in YYYY-MM-DD format."]

How can we validate the user input with request.method =='GET'? (similar to using "clean_method" on POST)

Thanks in advance!

views.py

class BookingListView(generic.ListView):
    model = Item
    template_name = 'booking.html'

    def get_queryset(self):
        from_date = self.request.GET.get('from_date')
        to_date = self.request.GET.get('to_date')
        guests_qty = self.request.GET.get('guests_qty')

        booked = (
            Q(booking__from_date__gte=from_date) |
            Q(booking__to_date__lte=to_date)
        )

        if from_date and to_date and guests_qty:
            return Item.objects.filter(persons=guests_qty).exclude(booked)
        elif from_date and to_date:
            return Item.objects.exclude(booked)
        else:
            return Item.objects.all()

HTML

<form action="{% url 'availability' %}" method="GET" novalidate>
<formset>
    <legend><h6>Available items</h6></legend>
    <div class="row">
        <div class="input-field col s12">
            <input id="id_from_date" type="text" name="from_date" autocomplete="off">
            <label class="" for="id_from_date">Arrival:</label>
        </div>
        <div class="input-field col s12">
            <input id="id_to_date" type="text" name="to_date" autocomplete="off">
            <label class="" for="id_to_date">Departure:</label>
        </div>
        <div class="input-field col s5">
            <input id="id_guests_qty" type="number" min="1" max="5" name="guests_qty" autocomplete="off">
            <label class="" for="id_guests_qty">Persons:</label>
        </div>
        <div class="input-field col s12">
            <button class="btn" type="submit">
                Search
            </button>
        </div>
    </div>
</formset>
</form>
Kevin D.
  • 315
  • 2
  • 19
  • you need to parse the date you get from the get to a datetime object. See [this answer](https://stackoverflow.com/questions/466345/converting-string-into-datetime) for the how to – Matt Jan 04 '19 at 22:07
  • Dear Matt, thank you for your quick reply, I've read the answer you're referring to and applied the "strptime" parsing method. I have to say this only works for a single specific date. Is their maybe a convenient way to validate the allowed characters used in the datefield or do we have to use javascript for this? – Kevin D. Jan 05 '19 at 17:04

0 Answers0