Django 管理员.在更改选择字段上隐藏字段

2022-01-25 00:00:00 python django django-models django-admin

问题描述

我有模特:

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

在管理页面我有 selectField 选项:value1",value2",value3",...当我选择value2"时,我需要显示 verified 字段.我该怎么做?

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?


解决方案

您需要添加一些 JavaScript 才能显示或隐藏该字段.jQuery 1.9.1 已经通过 在 Django admin 中可用django.jQuery 对象.

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.

添加此 JavaScript 的最简单方法是添加 媒体 元类到您的模型表单并将表单添加到 ModelAdmin:

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);

相关文章