Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Admin disable field dynamically based on other selections

I've built a django model where the required fields change based upon the user's selection on other previous fields. Specifically, it is an event scheduling application where the options change based on choices the user makes.

Some combinations of fields are simply invalid, and I have the model set to check for those and not allow them. However, it is a bit confusing in the UI to figure out the right combinations. I would like the admin UI to help with this by hiding or disabling invalid fields as the user changes other fields.

For example, if the user chooses to make the event repeat weekly, I need to disable (or ideally remove) all of the daily and monthly fields and only show the weekly ones, such as day of week.

Also, if they go back and change it to daily, then the fields that are shown or enabled need to change to reflect that selection.

How would I set up the admin form so that this happens? I know this is doable through the DOM and javascript, but I am trying to determine if there is a mechanism for this built in to Django. I've been searching the Django docs, but I can't seem to find it.

Does anyone have an example showing how you have done similar things?

like image 683
Jon Avatar asked Feb 17 '12 14:02

Jon


1 Answers

There's no build in solution.

Simple solution is to add custom JavaScript code to your admin. See the reference here. Simply add the js and css files to the Admin class and script the form in your custom js.

class ReportAdmin(admin.ModelAdmin):

    class Media:
        js = (
            'frontend/js/jquery-1.6.1.min.js',
            'frontend/js/jquery-ui.min.js',
            'frontend/js/custom_js.js',
        )
like image 93
Mariusz Jamro Avatar answered Oct 11 '22 15:10

Mariusz Jamro