Skip to content

Instantly share code, notes, and snippets.

@milinmestry
Created August 17, 2017 13:11
Show Gist options
  • Save milinmestry/71bde7211ba8a0c44dc4c519de1c9fb8 to your computer and use it in GitHub Desktop.
Save milinmestry/71bde7211ba8a0c44dc4c519de1c9fb8 to your computer and use it in GitHub Desktop.
Django Admin Form - show/hide div based on option selected
I am using Django version 1.11
In the created app, add directory to store (static) JavaScript file(s) in it.
In my case I have created "div_showhide.js" file in this location-
MY_APP_NAME/static/MY_APP_NAME/js/admin/div_showhide.js
New directories are:
static/
MY_APP_NAME/
js/
admin/
Refer this URL for more details about static files in Django.
https://docs.djangoproject.com/en/1.11/howto/static-files/
In the created app (MY_APP_NAME) open "admin.py" file, and create a class related to Model.
In my case I am using model as "Question" so my class file code looks like this-
from django.contrib import admin
...
class QuestionAdmin(admin.ModelAdmin):
form = QuestionForm
....
....
....
class Media:
js = ("MY_APP_NAME/js/admin/div_showhide.js", )
Here the important part in the above code is "class Media" wherein we are
setting the JavaScript file(s) to be loaded in this Model form in the Djanog
Admin panel.
The "QuestionForm" is created in "forms.py" file.
Now add your logic in the JavaScript file.
To use jQuery related code, please read how Django use jQuery in Admin from this URL-
https://docs.djangoproject.com/en/1.11/ref/contrib/admin/#jquery
Special Thanks to:
https://stackoverflow.com/questions/18678711/dynamic-show-and-hide-fields-in-django-admin-panel
https://stackoverflow.com/questions/26139206/django-admin-hide-field-on-change-select-field
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment