Skip to content Skip to sidebar Skip to footer

Django Admin Show / Hide Fields If Specific Value Is Selected In A Dropdown

In the Django admin, when the choice Custom is selected from a dropdown list, I want to display the inline start_date and end_date fields to allow the user to specify a specific st

Solution 1:

Purpose of this question: to show / hide a fieldset if a specific option is selected in a Django admin form dropdown.

Solution overview: you need to break fieldsets up into two instead of one, custom javascript, define Media class in ModelAdmin.

[Step One] In my project named dropdown, I added the following folders / files:

  • static (directory)
  • static/dropdown (directory)
  • static/dropdown/js (directory)
  • static/dropdown/js/base.js (file)

[Step Two] In admin.py, a few things to note:

  1. I broke fieldsets up into two instead of one.
  2. Notice that I'm defining classes for each fieldset. abcdefg is the name of the class of the fieldset I'm trying to show and hide.
  3. I defined class Media. This tells django where to look for custom javascript and css files.

admin.py

from django.contrib import admin
from dropdown.models import DropdownModel
from dropdown.forms import DropdownModelForm

classDropdownModelAdmin(admin.ModelAdmin):

    fieldsets = (
        ('Date Range', {
            'fields': ('date_range',),
            'classes': ('predefined',)
        }),
        (None, {
            'fields': (('start_date', 'end_date'),),
            'classes': ('abcdefg',)
        })
    )

    form = DropdownModelForm

    classMedia:
        js = ('dropdown/js/base.js',)

admin.site.register(DropdownModel, DropdownModelAdmin)

[Step Three] Add javascript. I take no credit for this script; I only modified it slightly from here.

base.js

(function($) {
    $(function() {
        var selectField = $('#id_date_range'),
            verified = $('.abcdefg');

        functiontoggleVerified(value) {
            if (value === 'Custom') {
                verified.show();
            } else {
                verified.hide();
            }
        }

        // show/hide on load based on existing value of selectFieldtoggleVerified(selectField.val());

        // show/hide on change
        selectField.change(function() {
            toggleVerified($(this).val());
        });
    });
})(django.jQuery);

[Step Four]

forms.py

from django import forms
from dropdown.modelsimportDropdownModelclassDropdownModelForm(forms.ModelForm):

    classMeta:
        model = DropdownModel
        fields = ('date_range',)
        widgets = {
            'date_range': forms.Select(choices=DropdownModel.CHOICES)
        }

Post a Comment for "Django Admin Show / Hide Fields If Specific Value Is Selected In A Dropdown"