我有模特:
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
字段。我该怎么办?
答案 0 :(得分:7)
您需要添加一些JavaScript才能显示或隐藏字段。 jQuery 1.9.1已经通过django.jQuery
对象available in Django admin。{/ p>
添加此JavaScript的最简单方法是在模型表单中添加Media元类,并将表单添加到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);