1 | initial version |
To implement Django Chained Dropdown on Django admin, follow these steps:
Install the django-smart-selects
package by running the command pip install django-smart-selects
in your command prompt.
Add 'smart_selects'
to the INSTALLED_APPS
list in your project's settings.py
file.
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
.
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)
Child
object, the parent dropdown will show only the parents that have been selected in the parent dropdown of other Child
objects.