Modifying some Django admin behaviors regarding their generated forms


I have a model which I am manipulating through the Django administrator.

The model and "its business logic" requires me to establish a specific behavior regarding its form to enter data. What I need to do is the following:

I have the following fields:

What I want to do is that when I select a name in the field Name , according to the selected value, I will display certain information (which will also be selected) in the fields Type , Freedom Degrees

It is something similar to when one in the registration forms, selects a country and according to that country, depart the departments / states / provinces and according to the selected depart cities or municipalities.

This I want to do for the administration module that Django provides, and I would also do it in my application properly. I know there are some things for customize the administration interface or working with ModelAdmin.form to add behaviors

I wanted to share this concern, in case someone has done things like that and if I'm on the right track.

asked by bgarcial 01.02.2016 в 22:24

1 answer


The package Django Smart Select does all the magic you're looking for

The example is from countries, exactly:

class Continente(models.Model):
        nombre = models.CharField(max_length=255)

class Pais(models.Model):
        continente = models.ForeignKey(Continente)
        nombre = models.CharField(max_length=255)

class Ubicacion(models.Model):
    continente = models.ForeignKey(Continente)
    pais = models.ForeignKey(Pais)
    area = models.ForeignKey(Area)
    ciudad = models.CharField(max_length=50)
    calle = models.CharField(max_length=100)

The package requires you to use a custom field type, which makes the package work:

from smart_selects.db_fields import ChainedForeignKey 

class Ubicacion(models.Model)
    continente = models.ForeignKey(Continente)
    pais = ChainedForeignKey(
    area = ChainedForeignKey(Area, chained_field="pais", chained_model_field="pais")
    city = models.CharField(max_length=50)
    street = models.CharField(max_length=100)

The chained_field property indicates which field you link in the current model and chained_model_field is the field in the other model.

You just have to follow the installation instructions.

  • Add smart_selects to your INSTALLED_APPS .
  • Create the routes in of smart_selects so that the chained Select controls work, for example:

    urlpatterns = patterns('',
        url(r'^admin/', include(,
        url(r'^chaining/', include('smart_selects.urls')),
  • It's more complicated with Many to Many fields, but the basic operation is this.

    answered by 01.02.2016 / 23:43