How to Create Dependent Dropdown List in Django?

Published On: 10/01/2023 | Category: Django


Hi Dev,

I will explain step by step tutorial how to create dependent dropdown list in django. Here you will learn how to create dynamic dropdown in django. step by step explain django chained dropdown list. We will look at example of django country state city dropdown.

In this example, we'll build a dynamically dependent dropdown in a django app for a country, state, and city. We'll design a straightforward form with three dropdown menus. The state will populate in the following dropdown when you choose the country, and the city will do the same when you choose the state. It is an easy example and step-by-step. So let's complete this example by following the steps below.

Here i will give you we will help you to give example of how to create dependent dropdown list in django. So let's see the bellow example:

Step 1: Create a Project

In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:

django-admin startproject example
Step 2: Create a App

Now we'll create a single app called core to store a list of post names. We're keeping things intentionally basic. Stop the local server with Control+c and use the startapp command to create this new app.

cd example
django-admin startapp core
Step 3: Update setting.py

Then update INSTALLED_APPS within our settings.py file to notify Django about the app.

settings.py

....
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'core',
]
Step 4: Create a Model

Now go for the creating models we will call our three model Country, State, City. so, following the below code in your project.

core/models.py
from django.db import models

# Create your models here.
class Country(models.Model):
    name = models.CharField(max_length=30)

    def __str__(self):
        return self.name

class State(models.Model):
    name = models.CharField(max_length=30)
    country = models.ForeignKey(Country, on_delete=models.CASCADE)

    def __str__(self):
        return self.name

class City(models.Model):
    name = models.CharField(max_length=100)
    state = models.ForeignKey(State, on_delete=models.SET_NULL, null=True)

    def __str__(self):
        return self.name

Ok, all set. We can engender a migrations file for this change, then integrate it to our database via migrate.

python manage.py makemigrations
python manage.py migrate
Step 5: Creating the Dummydata

The dumpdata command dumps data from the database into the standard output, serialized in JSON format by default. The resulting data structure includes information about the model and its fields for Django to be able to load it into the database to following command.

In this core/fixtures project directory create a db.json file.

python manage.py loaddata db.json

So, open your db.json file and add to this code.

[
{
  "model": "core.country",
  "pk": 1,
  "fields": {
    "name": "India"
  }
},
{
  "model": "core.country",
  "pk": 2,
  "fields": {
    "name": "United States"
  }
},
{
  "model": "core.state",
  "pk": 1,
  "fields": {
    "name": "Gujarat",
    "country": 1
  }
},
{
  "model": "core.state",
  "pk": 2,
  "fields": {
    "name": "Maharashtra",
    "country": 1
  }
},
{
  "model": "core.state",
  "pk": 3,
  "fields": {
    "name": "California",
    "country": 2
  }
},
{
  "model": "core.city",
  "pk": 1,
  "fields": {
    "name": "Rajkot",
    "state": 1
  }
},
{
  "model": "core.city",
  "pk": 2,
  "fields": {
    "name": "Mumbai",
    "state": 2
  }
},
{
  "model": "core.city",
  "pk": 3,
  "fields": {
    "name": "Ahmedabad",
    "state": 1
  }
},
{
  "model": "core.city",
  "pk": 4,
  "fields": {
    "name": "Sacramento",
    "state": 3
  }
}
]
Step 6: Creating the Views

In this step, we need to configure views. open the core/views.py file and add.

core/views.py
from django.shortcuts import render
from .models import Country, State, City
from django.http import HttpResponse, JsonResponse, HttpResponseRedirect
import json

# Create your views here.
def index(request):
    countries = Country.objects.values('id','name')
    return render(request,"dropdown.html",{'countries':countries})

def fetch_state(request):
    country_id = request.POST.get('country_id')
    states = list(State.objects.filter(country_id=country_id).values('name','id'))
    return JsonResponse({'states':states},safe=False)

def fetch_city(request):
    state_id = request.POST.get('state_id')
    cities = list(City.objects.filter(state_id=state_id).values('name','id'))
    return JsonResponse({'cities':cities},safe=False)
Step 7: Creating the Templates

Next, then with your text editor create new templates files: core/templates/dropdown.html file and the add:

core/templates/dropdown.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="csrf-token" content="content">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>How to Create Dependent Dropdown List in Django? - Tuts-Station.com</title>
    <!-- CSS only -->
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container mt-5">
        <div class="row justify-content-center">
            <div class="col-md-9">
                <div class="alert alert-primary mb-4 text-center">
                   <h4>How to Create Dependent Dropdown List in Django? - Tuts-Station.com</h4>
                </div> 
                <form>
                    <div class="form-group mb-3">
                        <select  id="country-dropdown" class="form-control">
                            <option value="">-- Select Country --</option>
                            {% for country in countries %}
                                <option value="{{country.id}}">
                                    {{country.name}}
                                </option>
                            {% endfor %}
                        </select>
                    </div>
                    <div class="form-group mb-3">
                        <select id="state-dropdown" class="form-control">
                        </select>
                    </div>
                    <div class="form-group">
                        <select id="city-dropdown" class="form-control">
                        </select>
                    </div>
                </form>
            </div>
        </div>
    </div>
  
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function () {
  
            /*------------------------------------------
            --------------------------------------------
            Country Dropdown Change Event
            --------------------------------------------
            --------------------------------------------*/
            $('#country-dropdown').on('change', function () {
                var idCountry = this.value;
                $("#state-dropdown").html('');
                $.ajax({
                    url: "{% url 'fetch_state' %}",
                    type: "POST",
                    headers: {
                        "X-CSRFTOKEN": "{{ csrf_token }}"
                    },
                    data: {
                        country_id: idCountry,
                    },
                    dataType: 'json',
                    success: function (result) {
                        $('#state-dropdown').html('<option value="">-- Select State --</option>');
                        $.each(result.states, function (key, value) {
                            $("#state-dropdown").append('<option value="' + value
                                .id + '">' + value.name + '</option>');
                        });
                        $('#city-dropdown').html('<option value="">-- Select City --</option>');
                    }
                });
            });
  
            /*------------------------------------------
            --------------------------------------------
            State Dropdown Change Event
            --------------------------------------------
            --------------------------------------------*/
            $('#state-dropdown').on('change', function () {
                var idState = this.value;
                $("#city-dropdown").html('');
                $.ajax({
                    url: "{% url 'fetch_city' %}",
                    type: "POST",
                    headers: {
                        "X-CSRFTOKEN": "{{ csrf_token }}"
                    },
                    data: {
                        state_id: idState,
                    },
                    dataType: 'json',
                    success: function (res) {
                        $('#city-dropdown').html('<option value="">-- Select City --</option>');
                        $.each(res.cities, function (key, value) {
                            $("#city-dropdown").append('<option value="' + value
                                .id + '">' + value.name + '</option>');
                        });
                    }
                });
            });
  
        });
    </script>
</body>
</html>
Step 8: Creating URLs

In this section, we need a urls.py file within the core app however Django doesn't create one for us with the startapp command. Create core/urls.py with your text editor and paste below code.

core/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('dropdown', views.index, name='index'),
    path('fetch-state', views.fetch_state, name='fetch_state'),
    path('fetch-city', views.fetch_city, name='fetch_city'),
]

Next, we require to add a URL path for our core app which can be done by importing include and setting a path for it.

example/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('core.urls')),
]
Run the Server

In this step, we’ll run the local development server for playing with our app without deploying it to the web.

python manage.py runserver

Next, go to the http://localhost:8000/dropdown address with a web browser.

I Hope It will help you....