Django admin. Displaying a hierarchical dropdown filter

后端 未结 2 1692
温柔的废话
温柔的废话 2021-01-06 13:35

I have the following model:

from django.db import models

class State(models.Model):
    name = models.CharField(max_length=30)
    abbreviation = models.Cha         


        
2条回答
  •  借酒劲吻你
    2021-01-06 13:57

    You need to create a custom widget to pick the City model (that is, your model should FK to City and not to State), this widget contains two Select fields, the first one contains the Sstates and the second one gets loaded on the pick of a State (you will need to plug a view to return Cities based on State ID to populate your City select).

    You should set your widgets Media inner class point to the specific .js file chaining both Selects.

    In the ModelAdmin specification, set your field's widget to the custom widget you just created and it's media will be automatically added to the change_form template.

    Make sure that your .js file looks for your regular JQuery object and falls back to django.JQuery, this way you can use this same widget in the admin and through out your site.

    (function($) {
    // Note that this function works only for one widget per page
    $('#state').change(function(){
        $('#city').load('/cities_by_state/', {id: this.value}); // the endpoint returns HTML
    });
    })(JQuery||django.JQuery);
    

    I've done something similar in an app I use locally for my projects (variable depth up to three levels) and the resulting solution ended up a bit hairy as it had to support multiple widgets per page, dynamic widgets (for inlines), templatetags to render the widget in various forms, etc.

提交回复
热议问题