因此,我有一个简单的列表视图,并覆盖了查询集,以包括表单字段供用户搜索特定的可用项目。
我正在使用过滤列表结果的方法; request.method =='GET',我知道我可以检查任何字段是否为空并显示所有结果或不显示任何结果。
我在使用DateField()时遇到问题,当我不使用日期格式“ YYYY / MM / DD”时,Django抛出ValidationError;
[“'02/10/2019'”值的日期格式无效。该格式必须为 YYYY-MM-DD格式。“]
我们如何使用request.method =='GET'验证用户输入? (类似于在POST上使用“ clean_method”)
谢谢!
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()
<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>