本文介绍了Django 管理员.在更改选择字段上隐藏字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!
问题描述
我有模特:
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);
这篇关于Django 管理员.在更改选择字段上隐藏字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!
本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!