DEV Community

Cover image for Using Django Filters
Htown
Htown

Posted on

Using Django Filters

Get the header image? Cause it's a Coffee filter... and I'm talking about Django filters. Plus, I like coffee.

Anyways... on to the point.

I recently was working on a page and implemented some basic filters to set things based on city / state and thought it would be of interest to some.

The page featured select boxes where you can choose each and then go to a city or state specific page. For instance, this page features car shows in Houston. You can see each selection is active.

Screen Shot 2020-10-27 at 8.32.06 AM

So the first step here is to create the form on the front end (using templates or whatever your stack is) for the states.

<div class="form-inline" id="locationFilter" data-cities-url="{% url 'events:load_cities' %}">
<select id="id_state" name="state" class="form-control ml-2 mb-2">
<option value="">Select State</option>
... add options ...
</select>

Then leave the city one blank to start, and fill it dynamically based on the state selection.

<select id="id_city" name="city" class="form-control ml-2 mb-2">
<option value="">Select City&nbsp;&nbsp</option>
</select>

Then you want to use JS to load the city list once a state is created. Here you just use the data-cities-url attribute and send an AJAX or API call to get the list of cities and update that list with the elements.

def load_cities(request):
Locality.objects.filter(state__code=state).order_by('name').values_list('name', flat=True).distinct()
return render(request, 'events/city_dropdown_list_options.html', {'cities': cities})

Here I use a template that contains the basic code for generating the dropdown list given the cities and you're good to go!

We have found this basic city state filter really helps our users quickly find things based on their area. It is also beneficial for SEO because you can segment content that may be location based into groups. So our users who may be looking for a cars and coffee houston meetup don't have to sift through all the options from across the country.

Eventually I want to add a self-completing text field so you don't have to use the dropdowns. Especially for the city selection as there can end up being quite a few of those.

Top comments (0)