0

I'm using Django's built-in Admin functionality to support a web app's admin users.

So far I'm also using mixins and "rest_framework - viewsets" library to have automated a generic CRUD API.

In my admin.py files, I've used fieldsets to easily create a nice form to add new records with automatically included dropdowns, checkboxes, dateboxes etc. Great.

A recent concern is that some of these some item selections should dictate the available options of other items.

For example, if a person selects a state/province, the list of available cities should be restricted to those in just that state/province, instead of all the cities in the database.

Is there any way to implement this behavior within the fieldsets syntax / without having to abandon viewsets and revert to manually coding this behaviour?

Edit #1: To be clear, my working application has no forms.py. So I'm looking for a solution that effects only models.py, admin.py, or views.py

Edit #2: Provided code examples.

Problem: After selecting State, "city" dropdown still shows all available cities, not specific to country selected above.

Sample admin.py

class SiteAdmin(ImportExportModelAdmin):
    fieldsets = (
        (Region, {
            'fields': ('State/Province')
        }),
        ('SubArea, {
            'fields': ('City'),
        }),
    )

Sample views.py

class SiteViewSet(viewsets.ReadOnlyModelViewSet):
    """
    A simple ViewSet for viewing accounts.
    """
    queryset = Site.objects.all()
    serializer_class = SiteSerializer

Sample models.py

class State(models.Model):
    name = models.CharField(max_length=100)


class City(models.Model):
    name = models.CharField(max_length=100)
    state = models.ForeignKey(state, on_delete=models.CASCADE,)
André Foote
  • 366
  • 3
  • 15
  • I think this might be what you're looking for: https://simpleisbetterthancomplex.com/questions/2017/03/22/how-to-dynamically-filter-modelchoices-queryset-in-a-modelform.html – michjnich Mar 22 '21 at 11:00
  • What you want is django-autocomplete-light https://django-autocomplete-light.readthedocs.io/en/master/ – unlockme Mar 22 '21 at 11:30
  • @Andre Foote, django-autocomplete-light will do exactly what you want to do. I apologize, I don't have to time to go through integrating it and showing you on the admin how it works. Take the time look at the documentation and code. I use it a lot, checkout this video https://www.youtube.com/watch?v=fJIHiqWKUXI. If I get some time maybe over the next week, I can come back to do a demo solution for ya. Dont count on that. – unlockme Mar 22 '21 at 14:21

0 Answers0