How to Create Cascading/Dependent Dropdown List in Django Python

In this tutorial, we will learn How to Create a Cascading/Dependent Dropdown List in Django Python. In this small application, we are going to improve user experience by Creating a dynamic Django dropdown list using jQuery.

Create a Django Dropdown project 

                We need to create a Django project  dropdownfill

               Django-admin startproject dropdownfill

Create Django App

                Now then need to create an app dropdown to perform the Cascading/Dependent Dropdown List in Django Python.

                 python  manage.py startapp dropdownfill

Configure  Application Settings

                Configure application settings by registering the App_name into the settings.py in a specific location at INSTALLED_APPS

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'dropdown',
]

Create the Model

Now we need to create models.py .

from django.db import models
from django.db.models.base import Model
from django.db.models.deletion import CASCADE

# Create your models here.


class department(models.Model):
    departmentname = models.CharField(max_length=100)


class employee(models.Model):
    deptid = models.ForeignKey(department,on_delete=CASCADE)
    empname = models.CharField(max_length=100)
    age = models.IntegerField()
    address = models.CharField(max_length=500, null=True)
    contactno = models.CharField(max_length=20) 

Create the views functions

views.py

from django.http.response import HttpResponse, JsonResponse
from django.shortcuts import render 
from .models import department,employee 
from django.core import serializers
import json

# Create your views here.

def getdata(request):
    template_name = 'dropdown.html'
    deptcontext = department.objects.all()
    empcontext = employee.objects.all()    

    return render(request,template_name,{'department':deptcontext,                                   'employee':empcontext})

https://labpys.com/how-to-upload-files-images-in-django-python/

Provide Routing (URL patterns)

We need to add dropdown.urls  to main project urls.py

urls.py

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('dropdown.urls')),
]

Create urls.py file inside  dropdown  app to write the URL pattern or providing routing for the application.

urls.py

from django.urls.conf import path
from dropdown import  views 

urlpatterns = [    
    path('getdata/',views.getdata,name="getdata"), 
]

Create Template

            Create a template folder inside  dropdown app and create html file in the directory.

dropdown.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DropDown</title>
   
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>

    <h1><center>How to Create Cascading/Dependent Dropdown List in Django python</center></h1>

  <div class="container">
  <div class="card body">
    <br/>
    <br/>
    <br/>
   
    <div class="row">
    <div class="col-md-4">
        
        <select name="dept" id="department" class="form-control">       
            <option value="0">--Select Department--</option>     
            {% for item in department  %}
            <option value="{{ item.id }}">{{ item.departmentname }}</option>
            {% endfor %}
        </select>
    </div>
  
    <br/>
    <div class="col-md-4">
        <select name="emp" id="Employee" class="form-control">
            <option value="0">--Select Staff--</option>  
            {% for item in employee  %}
            <option value="{{ item.deptid_id }}">{{ item.empname }}</option>
            {% endfor %}
        </select>
    </div>
 
   </div>
  </div>
</div>

 


<script>

$(document).ready(function(){

 var department = $("#department");
 var Employee = $("#Employee");
 var $options = Employee.find('option');
 department.on('change',function(){
    Employee.html($options.filter('[value="'+ this.value  +'"]'));
 }).trigger('change'); 


}); 
</script> 
</body>
</html>

Now make migrations

 Python manage.py makemigrations

Python manage.py migrate

Python manage.py runserver

Please leave your  comments and suggestion

One Comment on “How to Create Cascading/Dependent Dropdown List in Django Python”

  1. i need to implement this in my project.in my form.html page there is an option to select a district and accordingly the correspondant branches should appear while clicking on branches.could you please rearrange this for my page.my form page is as below.<!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
         {% load static %}
        <link href="{% static 'css/form.css' %}" rel="stylesheet" type="text/css">
        <script src="{% static 'js/form.js' %}" type="text/javascript"></script>
    </head>
    <body>
    <div class="container">
      <h1>Details verification</h1>
      <form name="registration" class="registartion-form" onsubmit="return formValidation()" method="=POST">
        {% csrf_token %}
    
    
        <table>
          <tr>
            <td><label for="name">Name:</label></td>
            <td><input type="text" name="name" id="name" placeholder="your name"></td>
          </tr>
          <tr>
            <td><label for="dob">DOB:</label></td>
            <td><input type="date" name="dob" id="dob" placeholder="DOB"></td>
          </tr>
          <tr>
            <td><label for="age">Age:</label></td>
            <td><input type="number" name="number" id="number" placeholder="Age"></td>
          </tr>
          <tr>
            <td><label for="gender">Gender:</label></td>
            <td>Male: <input type="radio" name="gender" value="male">
              Female: <input type="radio" name="gender" value="female">
              Transgender: <input type="radio" name="gender" value="Transgender"></td>
          </tr>
          <tr>
            <td><label for="phoneNumber">Phone Number:</label></td>
            <td><input type="number" name="phoneNumber" id="phoneNumber"></td>
          </tr>
          <tr>
            <td><label for="email">Email:</label></td>
            <td><input type="text" name="email" id="email" placeholder="your email"></td>
          </tr>
          <tr>
            <td><label for="password">Password:</label></td>
            <td><input type="password" name="password" id="password"></td>
          </tr>
          <tr>
            <td><label for="address">Address:</label></td>
            <td><textarea name="address" id="address" placeholder="Address"></textarea></td>
          </tr>
    
    
          <tr>
            <td><label for="district">District</label></td>
            <td>
              <select name="district" id="district" onchange="UpdateBranches(this.value)">
                <option value="">Select District</option>
                <option value="Thrissur">Thrissur</option>
                <option value="Ernamkulam">Ernamkulam</option>
                <option value="Palakkad">Palakkad</option>
                <option value="Kottayam">Kottayam</option>
                <option value="Trivandrum">Trivandrum</option>
              </select>
            </td>
          </tr>
          <tr>
            <td> <label for="branch">Branch:</label></td>
            <td>
              <select id="branch" name="branch">
                <option value="">Select Branch</option>
              </select></td>
          </tr>
          <tr>
            <td><label for="Account">Account Type</label></td>
            <td>
              <select id="account" name="account">
                <option value="">Choose</option>
                <option value="Savings">Savings</option>
                <option value="Current">Current</option>
              </select></td>
          </tr>
          <tr>
            <td><label for="material">Materials Required :</label></td>
            <td>
              <input type="checkbox" id="debit" name="materials[]" value="Debit Card">
              <label for="debit">Debit Card</label>
              <input type="checkbox" id="credit" name="materials[]" value="Credit Card">
              <label for="credit">Credit Card</label>
              <input type="checkbox" id="cheque" name="materials[]" value="Chequebook">
              <label for="debit">Cheque Book</label></td>
          </tr>
          <tr div class="button">
            <td colspan="2"><input type="submit" class="submit" value="Register" onclick="return formValidation()" /></td>
          </tr>
        </table>
      </form>
    </div>
    </body>
    </html>
    

Leave a Reply

Your email address will not be published. Required fields are marked *