Ad

How To Filter Foreingkey Choices In Django Admin?

- 1 answer

I have 3 simple models:

class Department(models.Model):
name = models.CharField(
    max_length=30
)


class Company(models.Model):
    name = models.CharField(
        max_length=30
    )
    department = models.ManyToManyField(Department)


class Employee(models.Model):
    name = models.CharField(
        max_length=30
    )

    company = models.ForeignKey(Company,
                                on_delete=SET_NULL,
                                null=True,
                                blank=True,
                                )

    department = models.ForeignKey(to=Department,
                                   on_delete=DO_NOTHING)

I want to restrict department options in Django Admin panel to those which are related to Employee's company. For example:

Departments:

HR, DevOpps, WebApps, TVApps

Companies:

Company_1 with departments - HR, DevOpps, WebApp

Company_2 with departments - HR, DevOpps, TVApps

Add Employee:

if Company_1 is selected, the options for department to be: HR, DevOpps, WebApp

if Company_2 is selected, the options for department to be: HR, DevOpps, TVApps

Ad

Answer

It sounds like you are looking to implement dependent dropdown in your forms?

Here is a great article I have followed in the past which you can use to address this by essentially filtering the options using ajax.

I have also seen this issue addressed nicely into htmx if you'd like to try that out. Their examples page shows the value-select being implemented.

Ad
source: stackoverflow.com
Ad