Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To implement Django Chained Dropdown on Django admin, follow these steps:

  1. Install the django-smart-selects package by running the command pip install django-smart-selects in your command prompt.

  2. Add 'smart_selects' to the INSTALLED_APPS list in your project's settings.py file.

  3. Create models for the two related models (parent and child) that you want to display as dropdowns. For example,

from django.db import models
from smart_selects.db_fields import ChainedForeignKey

class Parent(models.Model):
    name = models.CharField(max_length=50)

class Child(models.Model):
    parent = ChainedForeignKey(
        Parent,
        chained_field="parent",
        chained_model_field="id",
        show_all=False,
        auto_choose=True,
        null=True,
        blank=True,
    )
    name = models.CharField(max_length=50)

In the Child model, notice the ChainedForeignKey field that is imported from smart_selects.db_fields.

  1. Register the models in your admin.py file using smart_selects's ChainedModelAdmin. For example,
from django.contrib import admin
from .models import Parent, Child
from smart_selects.admin import ChainedModelAdmin

class ChildAdmin(ChainedModelAdmin):
    # Fields to be shown on the admin page
    list_display = ('name', 'parent',)
    # Fields to appear as dropdowns
    search_fields = ['name']
    # Fields to order the drop-down items
    ordering = ['name']
    # Fields to be shown as filters
    list_filter = ['parent']

admin.site.register(Parent)
admin.site.register(Child, ChildAdmin)
  1. Finally, run the server and go to the admin page to see the chained dropdowns in action. When adding or editing a Child object, the parent dropdown will show only the parents that have been selected in the parent dropdown of other Child objects.