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.Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2022-04-05 11:00:00 +0000
Seen: 8 times
Last updated: Jun 26 '22
What is the process to establish a connection between three Django models?
How can the data obtained through playwright-scrapy be stored in django models?
How to retrieve Django models using their model name?
How can multiple models be serialized in Django?
Can FastAPI/OpenAPI support multiple response models?
How can the local juypter book be connected to the school server for training models?