dependent dropdown in django

here is my html page. i need to use dependent dropdown for district and branches here.can you please help.

Title {% load static %}

Details verification

{% 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" class="district-dropdown">
        <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" class="branch-dropdown">
        <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>

This is a fairly common topic here in the forum. You can search and find a number of conversation on this topic.

As a starting point, see Dependent Drop Down and Values from the second field of the form - depending on the selected value of the first field? - #2 by KenWhitesell

Note, in general, you’re going to find this easier if you use Django forms and templates, rather than hand-constructing the full html.

forms.py…
from django import forms
from django.db import models

class RegistrationForm(forms.Form):
name = forms.CharField()
dob = forms.DateField()
age = forms.IntegerField()
gender = forms.ChoiceField(choices=[(‘male’, ‘Male’), (‘female’, ‘Female’), (‘transgender’, ‘Transgender’)])
phone_number = forms.CharField()
email = forms.EmailField()
password = forms.CharField(widget=forms.PasswordInput)
address = forms.CharField(widget=forms.Textarea)
district = forms.ChoiceField(choices=[(‘thrissur’, ‘Thrissur’), (‘ernamkulam’, ‘Ernamkulam’), (‘palakkad’, ‘Palakkad’), (‘kottayam’, ‘Kottayam’), (‘trivandrum’, ‘Trivandrum’)])
branch = forms.ChoiceField(choices=)
account_type = forms.ChoiceField(choices=[(‘savings’, ‘Savings’), (‘current’, ‘Current’)])
materials_required = forms.MultipleChoiceField(choices=[(‘debit’, ‘Debit Card’), (‘credit’, ‘Credit Card’), (‘cheque’, ‘Chequebook’)], widget=forms.CheckboxSelectMultiple)

views.py

def user_registration(request):
if request.method == ‘POST’:
form = RegistrationForm(request.POST)
if form.is_valid():
user = form.save() # This will save the user to the database
login(request, user) # This will log the user in
return redirect(‘registration_success’)
else:
form = RegistrationForm()

return render(request, 'form.html', {'form': form})

@require_GET
def get_branches(request):
district = request.GET.get(‘district’)
branches =
if district == ‘thrissur’:
branches = [‘Kunnamkulam’, ‘Kodugallur’, ‘Wadakkanchery’]
elif district == ‘ernamkulam’:
branches = [‘Angamaly’, ‘Perumbavoor’, ‘Vytilla’]
elif district == ‘palakkad’:
branches = [‘Chittur’, ‘Ottappalam’, ‘Kalpathy’]
elif district == ‘kottayam’:
branches = [‘Pala’, ‘Changanassery’, ‘Ponkunnam’]
elif district == ‘trivandrum’:
branches = [‘Atingal’, ‘Varkkala’, ‘Neyyattinkara’]

data = {'branches': branches}
return JsonResponse(data)

form.js
const districtSelect = document.getElementById(‘district’);
const branchSelect = document.getElementById(‘branch’);

districtSelect.addEventListener(‘change’, (event) => {
const selectedDistrict = event.target.value;
const url = /get_branches/?district=${selectedDistrict};

fetch(url)
.then(response => response.json())
.then(data => {
branchSelect.innerHTML = ‘’;
data.branches.forEach((branch) => {
const option = document.createElement(‘option’);
option.value = branch;
option.text = branch;
branchSelect.appendChild(option);
});
});
});
can you help me to find why the branch dropdown is not working there. district is working fine. but after selecting a district there is no branch lists. only ‘select branch’ is visible.

When posting code (or templates, error message etc) here, enclose the code (etc) between lines of three backtick - ` characters. This means you’ll have a line of ```, then your code (or template, etc), then another line of ```. This forces the forum software to keep your code properly formatted, which is critical with python.

You don’t need to repost your code above, you can edit it and add the ``` before and after the code. (Note that those lines must be lines by themselves and not part of any other line.)

As far as debugging this, what part of this isn’t working? Are you fetching the proper values and they’re just not rendering correctly? Or are you not even retrieving the right values?


here after running i am getting the result like this.my problem is when selecting a district from the dropdown its dependent branches are not visible.

I understand the description of the issue.

So, how do you debug this?

The first question is, where is it failing?

When you select a District:

  • Is it sending a request to the server?
    • Is it sending the right request?
  • Does the server send a response?
    • Is it sending the right response?
  • If your AJAX handler is receiving the correct response, is it processing it correct?
    • Does it have the data you’re expecting it to have in the format that it’s expecting?
1 Like