Django administrator. Hide field in change selection box

I have a model:

class CategoryField(models.Model):
    selectfield = models.IntegerField(choices=SELECT_FIELD_CHOICES, default=1)
    verified = models.BooleanField(default=True, verbose_name='Required?')


On the admin page I have selectField

with options: "value1", "value2", "value3", ... When I select "value2", I need to show the field verified

. How can i do this?


source to share

1 answer

You need to add JavaScript to show or hide the field. jQuery 1.9.1 is available in the Django admin via an object django.jQuery


The easiest way to add this JavaScript is to add the Media meta-focus to your model form and add the form to ModelAdmin



from django import forms

class CategoryFieldForm(forms.ModelForm):
    . . .

    class Media:
        js = ('category-field-admin.js',)


from django.contrib import admin

from your_app.forms import CategoryFieldForm
from your_app.models import CategoryField

class CategoryFieldAdmin(admin.ModelAdmin):
    form = CategoryFieldForm, CategoryFieldAdmin)

# category-field-admin.js

// pseudo code - change as needed

(function($) {
    $(function() {
        var selectField = $('#id_selectField'),
            verified = $('#id_verified');

        function toggleVerified(value) {
            value == 'value2' ? : verified.hide();

        // show/hide on load based on pervious value of selectField

        // show/hide on change
        selectField.change(function() {




All Articles