Django admin. Hierarchical Drop-Down Filter Display

I have the following model:

from django.db import models

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

    def numberOfCities(self):
        return self.city_set.count()

    def __unicode__(self):
        return u"{0} - {1}".format(self.abbreviation, self.name)

class City(models.Model):
    name = models.CharField(max_length=40)
    state = models.ForeignKey(State)

    class Meta:
        verbose_name_plural = 'Cities'

    def __unicode__(self):
        return self.name

class Company(models.Model):
    name = models.CharField(max_length=60)
    description = models.CharField(max_length=1000)
    city = models.ForeignKey(City)

    class Meta:
        verbose_name_plural = 'Companies'

    def __unicode__(self):
        return self.name;

As you can see, each company is associated with a city, and as you expect, the Django administrator creates a company creation form containing a drop-down list of cities. But to improve the user interface, I would like the user to first select a state, and then the city’s drop-down menu would be populated with cities from that state. Is there a standard way to do this?

+3
source share
2 answers

, ( FK City, State), Select, Sstates, ( , , ).

, Media .js , .

ModelAdmin , , change_form.

, .js JQuery django.JQuery, .

(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);

- , ( ), , , ( ), templatetags ..

+1

, django, . - :

  • ( change_form.html).
  • ajax-url, City, .
  • - jQuery City .

Django admin Javascript jQuery. , Django jQuery django.jQuery. , django.jQuery / .

+1

Source: https://habr.com/ru/post/1790363/


All Articles