Ask Your Question
2

How can Django Chained Dropdown be implemented on Django admin?

asked 2022-04-05 11:00:00 +0000

huitzilopochtli gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2022-06-26 08:00:00 +0000

scrum gravatar image

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.
edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2022-04-05 11:00:00 +0000

Seen: 8 times

Last updated: Jun 26 '22