-1

Like: There are three dropdowns: Country, Province, and District.

  1. Country: When I click on Country dropdown it'll display all the countries. And I'll choose one.
  2. Province: When I choose a Country, the Province gets filtered according to country and displays all the provinces on that chose country. And I'll choose a province.
  3. District: After choosing a province, the district gets filtered according to the districts inside that province.

I hope you got me. I want this to be possible in Django admin

1 Answers1

0

Possible solution without additional libs

Using raw_id_fields won't give you the select boxes as you describe but open a dialog from which it is possible to search for the district and select it. This is possible to do with the Django Admin directly and not additional libraries.

You did not provide the code for your models and the admin, so I'm assuming a very simple model structure to illustrate the solution.

Given these models:

class Country(Model):
    name = TextField(...)
    ....

class Province(Model):
    name = TextField(...)
    country = ForeignKey(..., unique=True)
    ....

class District(Model):
    name = TextField(...)
    province = ForeignKey(..., unique=True)
    ....

and some model that uses country:

class SomeLocation(Model):
    district = ForeignKey(..., unique=True)

I'm assuming that this model you want an admin UI for only needs the district field because this uniquely defines province and country. But for the user it might be easier to select the country and province first, instead of selecting from a huge list of districts.

Assumption: the selections of country and province are for better user experience.

If you enable the admin for SomeLocation:

from django.contrib.admin import register, ModelAdmin

@register(District):
class DistrictAdmin(ModelAdmin):
    list_display = ['name', 'province__name', 'province__country__name']
    list_filter = ['province', 'province__country']
    search_fields = ['name', 'province__name', 'province__country__name']

@register(SomeLocation)
class SomeLocationAdmin(ModelAdmin):
    ....
    raw_id_fields = ['district']
    

Solution with Selects

You will have to customize the Admin by using additional libs like https://pypi.org/project/django-ajax-selects/ or write your own logic including JS. This might be more effort than is warranted for an Admin UI.

Risadinha
  • 16,058
  • 2
  • 88
  • 91