Search code examples
djangoadminmodels

How can I dynamically change list of fields displayed in admin interface depending on the choice in the first field?


I want the admin interface to show disctrict field only if I choose 'B' as the category. If I choose 'W' I want all fields of Offer model to be displayed. Is it possible to show selected (filtered) fields in admin page depending on the choice in other field in the same model? Thanks in advance for your help.

My models:

class Category(models.Model):

NAME_CHOICES = (
    ('B', 'BLACK'),
    ('W', 'WHITE'),
)

name = models.CharField(max_length=200, choices=NAME_CHOICES)

class Meta:
    verbose_name_plural = 'Categories'

def __unicode__(self):
    return self.get_name_display()



class Offer(models.Model):

category = models.ForeignKey(Category, verbose_name='Kategoria')
city = models.CharField(max_length=128, verbose_name='Miasto')
province = models.CharField(max_length=3)
district = models.CharField(max_length=128, verbose_name='Dzielnica')

def __unicode__(self):
    return "Offer number %s" % (self.id)

Solution

  • First of all I must to tell, that django works only in sync way. So if you want to choose which input to use, you must send a request and wait a feedback. In my opinion there're no straight way to do this task correctly.

    And I see a few solutions:

    1) You can use jQuery for that. But the main problem is that django has a own admin system with a built-in widgets. You can try to customize it in two ways:

    • Take an app with this option (for example, django-admin-tools) and create custom behavior on your form;
    • manage.py collectstatic and after that going to admin folder and create custom jQuery script.

    2) Build a custom admin form for your model with ModelChoiceField. I don't quit sure about this field behavior really help you, but you can investigate that.

    If I need to do this task, I choose first way with admin static and custom jQuery.