How to Create a Chip with Filter in Django

In this Python tutorial, I will demonstrate to you how to create a chip with a filter in Django. You will learn to create a Django project based on the chip filter which is divided into two parts.

In the first part, you will create a simple chip with information like icons, text, and links using javascript dynamically. And in the second part, you will create a checkbox filter and cards which are also created dynamically based on the data fetch from the Django database.

So you will create a Django application, where when you click on the chip, it will show the information related to that chip on the next page as a card. And it will also show a checkbox filter that will show that you have clicked on this kind of chip.

How to Create a Chip with Filter in Django

First, set up a virtual environment ‘chip_env’ for the Django project using the below command.

python -m venv chip_env

Activate the ‘chip_env’ environment using the below code.

chip_env\Scripts\activate

After activating the environment, install Django.

python -m pip install django

Create a Django project ‘chip_filter’ using the given code.

django-admin startproject chip_filter .

Then create an app ‘app_chipfilter’.

django-admin startapp app_chipfilter
Create a Chip with Filter in Django Environment Setup and Project Creation

After setting up the environment and Django project, use the below command to create the default database and tables that come with Django.

python manage.py migrate
Create a Chip with Filter in Django Creating Database

Add the created app name in the setting file of the project as shown in the below picture.

INSTALLED_APPS = [
   ....,
   .....,
   'app_chipfilter',
]
App name in Setting File Create a Chip with Filter in Django

Create a model ‘Country’ in the file models.py of your app which is going to contain the country name, country code, country description (about the country), popular cities, and education rating.

from django.db import models

class Country(models.Model):
    country_name = models.CharField(null=True, max_length=100)
    country_code = models.IntegerField(null= True)
    country_description = models.CharField(null= True, max_length=200)
    popular_cities = models.CharField(null= True, max_length= 100, unique=True)
    education_rating = models.IntegerField(null=True)
    image_url = models.URLField(max_length=500)

    def __str__(self):
        return self.country_name
Create a Chip with Filter in Django Country Model

Register the Django model in the file admin.py of your app using the below code.

from django.contrib import admin
from .models import Country


admin.site.register(Country)
Register the app in admin file Create a Chip with Filter in Django

Let’s migrate the above model using the below code.

python manage.py makemigrations
python manage.py migrate 
Migrating model Country Create a Chip with Filter in Django

Create a simple view named ‘CountryFilter’ in the file views.py of your app that will return all the countries and their details.

from django.shortcuts import render
from django.views import View
from .models import Country
from django.core import serializers

class CountryFilter(View):
    def get(self, request):
        countries = Country.objects.all()
        countries_list = serializers.serialize('json', list(countries))
        context = {'countries': countries_list}
        return render(request,'index.html',context)
View Country Filter Create a Chip with Filter in Django

The view CountryFilter fetches the data from the table Country and stores it in the variable countries, then this data serialize (Serialization is the process where the objects are converted into data types) using the serialize() function of the module serializers.

Then passed as context to the template’s index.html using the render() function.

Create folder templates and in that folder make a file named ‘index.html’ and add the following code in the index.html file.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Chip Filter</title>
</head>
<body>
<div id="container">
  </div>
</body>

</html>
How to Create a Chip with Filter in Django Index Html File

This index.html file will show the chip filter with country icon, name, and link (on clicking which shows the information about that country).

Let’s add some functionality to this html file to show the chip filter using the javascript. So add the following code within <script> </script> tags after closing div tag </div> and before the closing body tag </body>.

<script>
    var countriesList = JSON.parse('{{ countries|safe }}');

    const mainArea = document.getElementById("container");
    countriesList.forEach(element => {
      chipFilter(element);
    });

    function chipFilter(element) {
      chipId = element.fields.country_name;
      console.log(chipId);

      const chipAreaDiv = document.createElement("div");
      chipAreaDiv.classList.add("chip-area");
      mainArea.appendChild(chipAreaDiv);

      const chipLogoDiv = document.createElement("div");
      chipLogoDiv.classList.add("chip-logo");
      chipAreaDiv.appendChild(chipLogoDiv);

      const chipLogoImg = document.createElement("img");
      chipLogoImg.src = `${element.fields.image_url}`;
      chipLogoDiv.appendChild(chipLogoImg);

      const txtDiv = document.createElement("div");
      txtDiv.classList.add("txt");
      chipAreaDiv.appendChild(txtDiv);

      const pElement = document.createElement("p");
      pElement.textContent = `${element.fields.country_name}`;
      txtDiv.appendChild(pElement);

      const chipLinkDiv = document.createElement("div");
      chipLinkDiv.classList.add("chip-link");
      chipAreaDiv.appendChild(chipLinkDiv);

      const linkElement = document.createElement("a");
      linkElement.id = "chipFilterLink";
      linkElement.href = "{% url 'chip-filter' 0 %}".replace("0", chipId);
      chipLinkDiv.appendChild(linkElement);
      const linkImg = document.createElement("img");
      linkImg.src = "https://imgtr.ee/images/2023/07/21/6cbc7bc38b2843f07ab2a66ffabc11c4.png";
      linkElement.appendChild(linkImg);
    }
  </script>
Create a Chip with Filter in Django Javscript Code

In the above code, ‘var countriesList = JSON.parse(‘{{ countries|safe }}’)’, This {{ countries|safe }} act as the placeholder for the JSON data. In general, this is {{ countries|safe }} the template tag in Django that helps in getting the data into the javascript environment.

Then the data is parsed into JSON objects using the function JSON.parse() and stored in the variable countriesList.

Then the function chipFilter() creates the required HTML element dynamically with information according to the data that exists in the countriesList. If there are three countries detailed in the variable countriesList, then it creates three chip filters with country icon, name, and link.

Let’s set up the Django URLs for the view so that you can access it on the browser after running the server. So first set the URLs for the Django project by opening the urls.py file, and using the below code.

from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('app_chipfilter.urls'))
]
Create a Chip with Filter in Django Project Level URLs Path

Also, set the URLs at the app level by creating a new urls.py file and adding the below code.

from django.urls import path
from .views import CountryFilter 

urlpatterns = [
    path('',CountryFilter.as_view(), name='country-filter'),
]
App URLs Path  Chip with Filter in Django

Now run the following command in the terminal to start the server.

python manage.py runserver

After starting the server, open your browser and enter the address http://127.0.0.1:8000/ and you see the page like this.

Create a Chip with Filter in Django Chip Filter

But you may not see this kind of icon, or text on your page if you haven’t inserted any data into the table CountryFilter that you created using the model.

The icon of the USA or the text ‘USA’ are fetched from the database and the link icon is specified manually using <a> tag containing an icon image link (which is stored on the cloud) in the index.html page using javascript code.

But the above chip filter doesn’t look like any chip, let’s give it some style to this filter using the CSS. Add the tag <style> </style> after closing the tag of the HTML element in the file index.html.

Within <style> </style> add the following code.

<style>
  #container {
    border: 3px solid #fff;
    padding: 20px;
  }

  .chip-area {
    background-color: #d1d5db;
    width: fit-content;
    height: 80px;
    display: flex;
    box-sizing: border-box;
    border-radius: 10px;
    padding: 10px;
    margin-right: 16px;
    float: left;
    transition: all 0.3s ease 0s;
  }

  .txt {
    justify-content: center;
    align-items: center;
    padding-left: 20px;
  }

  .txt p {
    justify-content: center;
    align-items: center;
    margin: 10px;
    font-size: 30px;
    font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
    color: black;
  }

  .chip-logo {
    align-items: center;
  }

  .chip-logo img {
    max-width: 100%;
    max-height: 100%;
    padding: 2px;
  }

  .chip-link {
    align-items: center;
    padding-left: 30px;
  }

  .chip-link img {
    max-width: 70%;
    max-height: 70%;
    padding: 10px;
  }

  .chip-area:hover {
    color: #494949 !important;
    border-radius: 50px;
    border-color: #494949 !important;
  }
</style>

After adding the style refresh the page, and you will see the chip filter like this.

Create a Chip with Filter in Django Chip Filter Styling

If you hover the mouse over the chip filter, it becomes a rounded chip filter. Now the first part of this project is completed. In the second part, you will make another page showing the checkbox filter with a card based on the checked filter.

Basically, when you click on the chip filter that is shown above, it will take you to another page that shows the checkbox filter on the left side of the page. And at the right of the checkbox filter, the card shows the information about the country image, title, popular cities, and body text.

Let’s start by creating a view ‘ChipFilter’ in the view.py file of your app using the below code.

class ChipFilter(View):
    def get(sefl, request, name):
        countries = Country.objects.all()
        countries_list = serializers.serialize('json', list(countries))
        countryData = Country.objects.filter(country_name = name)
        country_list = serializers.serialize('json', list(countryData))
        context = {'countries': country_list,'countries_list': countries_list}
        return render(request,'card-list.html',context)
View ChipFilter Create a Chip with Filter in Django

The ChipFilter View filters the country details based on the name. It serializes the data in the variable countries and also filters the specific country data and saves it into the variable countryData.

Then pass these data as context to the template ‘card-list.html’.

Now create the new HTML file ‘card-list.html’ in the templates folder of your app and the following code.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>List of Cards</title>
</head>

<body>
    <div id="filterContainer" data-type="checkbox">

    </div>

    
</body>
</html>

The page will show the checkbox filter and card which fetches information from the database based on the selected chip filter from the page ‘index.html’. So the checkbox filter and card will be generated dynamically using the functionality written in javascript.

So add the following code within <script> </script> tags after closing div tag </div> and before the closing body tag </body>.

<script>
        var countriesData = JSON.parse('{{ countries|safe }}');
        var countriesList = JSON.parse('{{ countries_list|safe }}');
        
        var Container = document.createElement("div");
        Container.id = "container";
        document.body.appendChild(Container);

        var filterContainer = document.getElementById("filterContainer");
        const filterHeading = document.createElement("div");
        filterHeading.classList.add("filterHeading");
        filterContainer.appendChild(filterHeading);
        const filterLabel = document.createElement("span");
        filterLabel.classList.add("country-heading");
        filterLabel.innerHTML = "Country Filter :";
        filterHeading.appendChild(filterLabel);

        countriesList.forEach(element => {
            filterContent(element);
         });

        countriesData.forEach((element) => {
            var CardContainer = document.createElement("div");
            CardContainer.id = "card-container";
            Container.appendChild(CardContainer);

            var img = document.createElement("img");
            img.src = `${element.fields.image_url}`;
            img.id = "image-data";
            CardContainer.appendChild(img);

            var cardDetails = document.createElement("div");
            cardDetails.id = "card-details";
            CardContainer.appendChild(cardDetails);

            var title = document.createElement("H2");
            title.innerHTML = `${element.fields.country_name}`;
            cardDetails.appendChild(title);

            var popularCities = document.createElement("span");
            popularCities.innerHTML = `Popular City: ${element.fields.popular_cities}`;
            popularCities.className = "tag";
            cardDetails.appendChild(popularCities);

            var countryDescription = document.createElement("p");
            var text = document.createTextNode(`${element.fields.country_description}`);
            countryDescription.appendChild(text);
            cardDetails.appendChild(countryDescription);

            checkedFilterBox(element.fields.country_name);
        });

        function filterContent(element) {
            const filterOption = document.createElement("div");
            filterOption.classList.add("filterOptns");
            filterContainer.appendChild(filterOption);

            const checkboxCount = document.createElement("div");
            checkboxCount.classList.add("chckBoxCont");
            filterOption.appendChild(checkboxCount);

            const inputType = document.createElement("INPUT");
            inputType.id = "checkbox-filter";
            inputType.className = `checkboxFilter-${element.fields.country_name}`;
            inputType.setAttribute('type', 'checkbox');
            checkboxCount.appendChild(inputType);

            const checkboxLabel = document.createElement("p");
            checkboxLabel.className = "country-name";
            checkboxLabel.innerHTML = `${element.fields.country_name}`;

            checkboxCount.appendChild(checkboxLabel);
        }
        
        function checkedFilterBox(data){
            var countrylabel = data;
        
        var getCheckboxFilter = document.getElementsByClassName(`checkboxFilter-${countrylabel}`);
        getCheckboxFilter[0].checked=true;}

    </script>
View ChipFilter Create a Chip with Filter in Django Javascript Code

After adding the functionality of generating checkbox filters and cards dynamically, It is time to specify the URLs for this view and html file in url.py of your app.

from django.urls import path
from .views import CountryFilter, ChipFilter

urlpatterns = [
    path('',CountryFilter.as_view(), name='country-filter'),
    path('chipfilter/<str:name>/',ChipFilter.as_view(), name = 'chip-filter')
]
Create a Chip with Filter in Django Setting URLs For ChipFilter View

After setting URLs, again start the Django server and click on any chip filter as shown in the below picture.

Create a Chip with Filter in Django

Look at the above picture, which shows the three-chip filter USA, Canada, and Brazil with icon, text, and link button. Click on any chip filter (for example on the USA), it will take you to the page as shown below.

Create a Chip with Filter in Django Checkbox Filter and Card

I clicked on the chip filter the USA, and on the next page, it shows the checked Country Filter option the USA, and the information about the country USA with image, title, popular city, and description.

It shows all the required information on the page but as we talked about, the checkbox filter should exist on the left side of the page and the card on the right side of the checkbox filter. But they are not, this is because we haven’t implemented the CSS style for that elements.

Let’s add some CSS style by adding the below code within the <style> </style> tag, Write this tag after the closing tag of HTML </html>.

<style>
    body {
        background-color: #eaeff1;
        font-family: "Raleway", sans-serif;
        display: flex;
    }

    #container {
        max-width: 300px;
        margin: 0 auto;
        margin-top: 20vh;
    }

    #card-container {
        margin-top: 20px;
        background-color: white;
        border: 1px solid #bacdd8;
        padding: 8px;
        border-radius: 12px;
        padding: 16px 8px 8px 8px;
    }

    #img-data {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        border-radius: 12px;
        object-fit: cover;
    }

    .tag {
        padding: 4px 8px;
        border: 1px solid #e5eaed;
        border-radius: 50px;
        font-size: 12px;
        font-weight: 600;
        color: #788697;
    }

    p {
        font-size: 14px;
        color: #7f8c9b;
        line-height: 150%;
        display: inline-block;
        width: 250px;
        white-space: nowrap;
        overflow: hidden !important;
        text-overflow: ellipsis;
        margin: 10px;
    }

    .filterContainer {
        display: flex;
        align-items: center;
        justify-content: center;
        height: fit-content;
        margin-top: 50px;
    }

    /* .filterOptns{
    display: flex;
    align-items: center;
    justify-content: center;
  } */
    .chckBoxCont {
        display: flex;
        align-items: center;
        justify-content: center;
        margin-top: 10px;
        padding-left: 15px;
    }

    .chckBoxCont input {
        padding-left: 15px;
        width: fit-content;
    }

    #checkbox-filter {
        padding-left: 15px;
        width: fit-content;
    }

    .chip-area{
       margin-top: 10px;
    }
</style>
Create a Chip with Filter in Django Checkbox Filter and Card Styling

After adding the style, refresh the page and you see the output like this.

Chip with Filter in Django Checkbox Filter and Card Styling

Now it looks good visually. Well, you have created the Chip Filter in Django successfully. And your chip filter should work like this.

Chip with Filter in Django

Conclusion

In this Python tutorial, you have learned about how to create a chip with a filter in Django, and also learn how to fetch data from the through view and use that data in the javascript code. Additionally, you have created the chip, checkbox filter, and cards based on that data dynamically.

You may like to read: