简体   繁体   中英

Django admin. Hide field on change select field

I have model:

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

In admin page I have selectField with choices: "value1", "value2", "value3", ... When I select "value2" I need to show verified field. How can I do it?

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

The simplest way to add this JavaScript is to add a Media meta class to your model form and add the form to the ModelAdmin :

# forms.py

from django import forms

class CategoryFieldForm(forms.ModelForm):
    . . .

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


# admin.py

from django.contrib import admin

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


class CategoryFieldAdmin(admin.ModelAdmin):
    form = CategoryFieldForm


admin.site.register(CategoryField, 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.show() : verified.hide();
        }

        // show/hide on load based on pervious value of selectField
        toggleVerified(selectField.val());

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM