article

Thursday, June 4, 2020

Django How to Filter QuerySets Dynamically using django-filter


Django How to Filter QuerySets Dynamically using django-filter

This tutorial is about how to use the django-filter to add a filtering to your views

I will implement a view to search for users.

Installation
install it with pip:


pip install django-filter settings.py
 
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp',
    'widget_tweaks',
    'django_filters',# pip install django-filter https://django-filter.readthedocs.org/en/latest/ 
]
filters.py
 
#filters.py
from django.contrib.auth.models import User
import django_filters

class UserFilter(django_filters.FilterSet):
    class Meta:
        model = User
        fields = ['username', 'first_name', 'last_name', ]
views.py
 
#views.py
from django.shortcuts import render, redirect

from django.contrib.auth.models import User
from myapp.filters import UserFilter

def search(request):
    user_list = User.objects.all()
    user_filter = UserFilter(request.GET, queryset=user_list)
    return render(request, 'user_list.html', {'filter': user_filter})
urls.py
 
#urls.py
from django.contrib import admin  
from django.urls import path
from myapp import views  
from django.conf.urls import url


urlpatterns = [  
    path('admin/', admin.site.urls),  
    url(r'^search/$', views.search, name='search'),
]
user_list.html
//templates/user_list.html
{% extends 'base.html' %}

{% load widget_tweaks %}

{% block content %}
  <form method="get">
    <div class="well">
      <h4 style="margin-top: 0">Filter</h4>
      <div class="row">
        <div class="form-group col-sm-4 col-md-3">
          {{ filter.form.username.label_tag }}
          {% render_field filter.form.username class="form-control" %}
        </div>
        <div class="form-group col-sm-4 col-md-3">
          {{ filter.form.first_name.label_tag }}
          {% render_field filter.form.first_name class="form-control" %}
        </div>
        <div class="form-group col-sm-4 col-md-3">
          {{ filter.form.last_name.label_tag }}
          {% render_field filter.form.last_name class="form-control" %}
        </div>
      </div>
      <button type="submit" class="btn btn-primary">
        <span class="glyphicon glyphicon-search"></span> Search
      </button>
    </div>
  </form>
  <table class="table table-bordered">
    <thead>
      <tr>
        <th>Username</th>
        <th>First name</th>
        <th>Last name</th>
        <th>Date joined</th>
      </tr>
    </thead>
    <tbody>
      {% for user in filter.qs %}
        <tr>
          <td>{{ user.username }}</td>
          <td>{{ user.first_name }}</td>
          <td>{{ user.last_name }}</td>
          <td>{{ user.date_joined }}</td>
        </tr>
      {% empty %}
        <tr>
          <td colspan="5">No data</td>
        </tr>
      {% endfor %}
    </tbody>
  </table>
{% endblock %}
templates/base.html
//templates/base.html
<!DOCTYPE html>
<html lang="en">
<head>
    {% load static %}
    <link rel="stylesheet" type="text/css" href="{% static 'css/bootstrap.css' %}"/>
    <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
 <title>{% block title %}Django How to Filter QuerySets Dynamically using django-filter{% endblock %}</title>
 <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet">
</head>
<body>
    <nav class="navbar navbar-default">
        <div class="container-fluid">
            <a class="navbar-brand">Cairocoders</a>
        </div>
    </nav>
 
 <div class="container">
    <div class="col-md-12 well">
        <h3 class="text-primary">Django How to Filter QuerySets Dynamically using django-filter</h3>
        <hr style="border-top:1px dotted #ccc;"/>
        {% block content %}
  
        {% endblock %}
    </div>
    </div>
    <script src="{% static 'js/jquery-3.1.1.min.js' %}"></script>
    <script src="{% static 'js/bootstrap.min.js' %}"></script>
</body>
</html>

Related Post