Create a hidden field in the admin site

前端 未结 5 786
孤街浪徒
孤街浪徒 2021-01-11 18:57

How can I create a fully hidden field (input and label) in the admin site? I know about the exclude property, but it fully excludes the field from the template,

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-11 19:45

    The Django admin does not support hidden fields yet. There is an open ticket for that: https://code.djangoproject.com/ticket/11277

    However, there are workarounds that don't require jQuery. The admin forms are rendered using admin/includes/fieldset.html. If you override this template, you can inject a CSS class to denote the row for hiding:

    this is actually a single line in the file, I've expanded it to make it more readable.

    ( Neat detail: for an StackedInline/TabularInline objects, you can specify the template as variable in Python code. )

    Next, you can hide that row in your CSS:

    .form-row.has-hidden-field {
        display: none;
    }
    

    Which you can load via your admin page:

    {% block extrastyle %}{{ block.super }}
    {% endblock %}
    

    or by using the media definition in the modeladmin:

    class Media:
        css = {'all': ('mysite/admin.css',)
    

提交回复
热议问题