我有一个与this question中描述的问题非常相似的问题。我已经实现了多个字段集的解决方案,并且效果很好。但是,尝试添加属于多个字段集的字段时遇到问题:
(admin.E012) There are duplicate field(s) in 'fieldsets[2][1]'.
在item_field2
和foo
中需要 bar
,但不需要baz
(因此它不能在初始字段集中)。我可以看到这是一个问题,但不确定如何解决。
admin.py
from django.contrib import admin
@admin.register(Item)
class ItemAdmin(admin.ModelAdmin):
fieldsets = (
# This first fieldset is always displayed
(None, {
'classes': ('item',),
'fields': ('item_type') # type is a select input with 'foo' and 'bar' options
}),
# Only one of the below fieldsets are displayed, depending on which item_type is chosen from the above select input
(None, {
'classes': ('foo',),
'fields': ('item_field1, item_field2')
}),
(None, {
'classes': ('bar',),
'fields': ('item_field2, item_field3')
}),
(None, {
'classes': ('baz',),
'fields': ('item_field4')
})
)
class Media:
js = ('admin.js',)
admin.js
window.addEventListener('load', function() {
(function($) {
var selectField = $('#id_item_type')
var foo = $('.foo');
var bar = $('.bar');
var baz = $('.baz');
function toggleVerified(value) {
if (value === '1') { // 'foo' selected
foo.show();
bar.hide();
baz.hide();
}
else if (value === '2') { // 'bar' selected
foo.hide();
bar.show();
baz.hide();
}
else if (value === '3') { // 'baz' selected
foo.hide();
bar.hide();
baz.show();
}
else { // Nothing selected yet
bar.hide();
foo.hide();
baz.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);
});