django admin 仅当复选框为 false 时才显示字段

标签 django django-admin

模型.py

class Menu(models.Model):

    ...
    has_submenu=models.BooleanField(default=1)
    page=models.ForeignKey(Page,null=True)

我希望 django admin 仅当 has_submenu 复选框为 false 时才显示页面属性(因此 django-admin 必须为我编写一些 javascript :) )

也许我必须扩展 render_change_form 方法

有什么建议吗?

最佳答案

您可以使用jQuery within the Django admin :

class MenuAdmin(admin.ModelAdmin):
    # ...
    class Media:
        js = ('/static/admin/js/hide_attribute.js',)

ModelAdmin and InlineModelAdmin have a media property that returns a list of Media objects which store paths to the JavaScript files for the forms and/or formsets.

hide_attribute.js 的内容:

hide_page=false;
django.jQuery(document).ready(function(){
    if (django.jQuery('#id_has_submenu').is(':checked')) {
        django.jQuery(".page").hide();
        hide_page=true;
    } else {
        django.jQuery(".page").show();
        hide_page=false;
    }
    django.jQuery("#id_has_submenu").click(function(){
        hide_page=!hide_page;
        if (hide_page) {
            django.jQuery(".page").hide();
        } else {
            django.jQuery(".page").show();
        }
    })
})

命名空间:

To avoid conflicts with user-supplied scripts or libraries, Django’s jQuery (version 3.3.1) is namespaced as django.jQuery.

关于django admin 仅当复选框为 false 时才显示字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15978719/

相关文章:

django - 在 Settings.py 中使用常量

python - 覆盖 django 管理员身份验证

python - 如果从不同的 View 函数调用,则不会传递上下文数据

python - Django 模板 block 未显示?

python - 在 Django 模型中添加一对多关系

Django raw_id_fields 小部件未显示搜索图标

Django - 是否建议用户使用代理模型?

python - 在 Django 1.6 管理更改列表中修改 "list_display_links"的 URL

python - ModelAdmin 中的 Django csrf_token

python - 无法编码 <type 'datetime.date' > 对象