Reputation: 75
How can I implement a Drop-Down search in Django where users can search through a listing of second hand cars. The HTML search page will have 3 dropdown search input for Brand, Colour, Year. Once users select a choice of brand, colour and year, the listings will return a list of cars that matches that requirement.
class SecondHandCar(models.Model):
brand = models.CharField(max_length=250, unique=True)
slug = models.SlugField(max_length=250, unique=True)
description = models.TextField(blank=True)
colour = models.CharField(Category, on_delete=models.CASCADE)
year = models.IntegerField(blank=False)
I would appreciate any ideas on what I need to do. I had a look at Q lookups, django haystack, but I'm unsure which would fit my needs. I think I would appreciate seeing how I could integrate this with the HTML side of things to pass the query from multiple input fields to Django.
Upvotes: 0
Views: 1261
Reputation: 3664
You can do this with a new endpoint where you can search the cars based on the required filters. I dont know if you want all of them combined to select cars or either one of which to be satisfied, because of which I have mentioned both.
Solution:
url(r'^search_cars/$'. views.search_cars, name='search-cars')
def search_cars(request, *args, **kwargs):
content_type = 'application/json'
# I think you only need ajax, but you can choose to remove this
if request.is_ajax():
brand = request.GET.get('brand')
colour = request.GET.get('colour')
year = request.GET.get('year')
# checking if all 3 are present
if brand is None or color is None or year is None:
return HttpResponse({
'success': False,
'message': 'Required fields are missing.'
}, content_type=content_type)
# depending on how you want to filter
# this will choose cars which have either brand, colour or year
filters = Q(Q(brand=brand) | Q(color=colour) | Q(year=year))
second_hand_cars = SecondHandCars.objects.filter(filters)
# or
# you can choose cars which satisfy all three of these together
filters = {'brand': brand, 'colour': colour, 'year': year}
second_hand_cars = SecondHandCars.objects.filter(**filters)
# serialize the objects and return the json response
data = []
for car in second_hand_cars:
data.append({
'brand': car.brand,
'colour': car.colour,
'year': car.year,
'description': car.description,
'slug': car.slug
})
return HttpResponse({
'success': True,
'data': data,
}, content_type=content_type)
else:
return HttpResponse({
'success': False,
'message': 'Only AJAX method is allowed.'
}, content_type=content_type)
// JavaScript code to make an ajax request
// when all three dropdowns are selected with appropriate values.
// assuming you are using jQuery.
// add a common class to all 3 dropdowns to monitor changes
$(document).on('change', '.filter-dropdown', function() {
# all three will provide attribute `value` of `option` tag.
var brand = $('#brandDropdown').children('option:selected').val();
var colour = $('#colourDropdown').children('option:selected').val();
var year = $('#yearDropdown').children('option:selected').val();
# add a default selected `option` tag with value `""`
if (brand !== "" && colour !== "" && year !== "") {
var data = {
'brand': brand,
'colour': colour,
'year': year
}
$.ajax({
url: '/search_cars/',
type: 'GET',
data: data,
dataType: 'json',
success: function(response) {
if (response.success) {
// render cars from `response.data`
} else {
// show message from `response.message`
}
},
error: function(errorResponse) {
// show error message
}
});
} else {
return;
}
});
Ref:
* AJAX Docs
* How to make an AJAX request without jQuery
* Q queries in Django
Upvotes: 1