Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic show and hide fields in Django admin panel

I have defined model in which one of the filed has definition:

REPEAT = (
    ('day', 'Daily'),
    ('week', 'Weekly'),
)

repeats = models.CharField('Repeat', default='day', max_length=5, choices=REPEAT)

Also I have defined related admin model, which is responsible to show my main model in panel.

Is possible to show and hide some fields in admin panel based on choice in repeats field? For example in scenery when user choose 'Daily', then some fields are not required and I want to hide them. I will be thankful for any advices or hints.

like image 492
Grzegorz Avatar asked Sep 07 '13 22:09

Grzegorz


1 Answers

Yes, you can add custom JS to your admin model:

class MyModelAdmin(admin.ModelAdmin):

    class Media:
        js = ("my_code.js",)

STATIC_URL is appended to your filename automagically.

And your JS function, assuming jQuery, something like:

$(function(){
$('<my-selector>').change(function(){
    //do something on select change
    });
});
like image 51
professorDante Avatar answered Nov 15 '22 09:11

professorDante