How To Filter Foreingkey Choices In Django Admin?
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:
HR, DevOpps, WebApps, TVApps
Company_1 with departments - HR, DevOpps, WebApp
Company_2 with departments - HR, DevOpps, TVApps
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
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.
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module