如何在 Django Admin 中隐藏 HiddenInput 小部件的字段标签?

2022-01-25 00:00:00 python django django-admin

问题描述

我有一些看起来像这样的 Django 表单代码:

I've got a bit of Django form code that looks like this:

class GalleryAdminForm(forms.ModelForm):
    auto_id=False
    order = forms.CharField(widget=forms.HiddenInput())

这使得表单字段消失了,但它在 Django 管理页面中留下了订单"标签.如果我使用:

And that makes the form field go away, but it leaves the label "Order" in the Django admin page. If I use:

order = forms.CharField(widget=forms.HiddenInput(), label='')

我仍然在字段和标签原来的位置之间留下:".

I'm still left with the ":" between where the field and label used to be.

我如何隐藏整个事情?!

How do I hide the whole thing?!


解决方案

如果您使用的是 JQuery,这应该可以解决问题:

If you're using JQuery this should do the trick:

您的表单

TO_HIDE_ATTRS = {'class': 'hidden'}
class GalleryAdminForm(forms.ModelForm):
    auto_id=False
    order = forms.CharField(widget=forms.TextInput(attrs=TO_HIDE_ATTRS))

要添加到模板的 JavaScript 代码

$(document).ready(function(){
    $('tr:has(.hidden)').hide();
});

如果您将表单呈现为表格,这将有效.如果您想让它与任何类型的表单渲染一起使用,您可以执行以下操作:

That works if you're rendering your form as a table. If you want to make it work with any kind of form rendering you can do as follows:

$(document).ready(function(){
    $('{{ form_field_container }}:has(.hidden)').hide();
});

并将 form_field_container 添加到您的模板上下文中.一个例子:

And add form_field_container to your template context. An example:

如果你这样渲染你的表单:

If you render your form like this:

    <form>
        <span>{{ field.label_tag }} {{ field }}</span>
    </form>

您的上下文必须包括:

'form_field_container': 'span'

你懂的……

相关文章