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

时间:2022-01-07 20:18:12

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

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

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

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

这使得表单字段消失了,但是它在Django管理页面中保留了标签“Order”。如果我使用:

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?!

我怎么能隐瞒整个事情?!

10 个解决方案

#1


-18  

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

如果你用的是JQuery,那么就应该这样做:

Your form

表单

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

Javascript code to add to your template

添加到模板的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();
});

And add form_field_container to your template context. An example:

并将form_field_container添加到模板上下文。一个例子:

If you render your form like this:

如果你像这样呈现你的表单:

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

Your context must include:

你的上下文必须包括:

'form_field_container': 'span'

You get the idea...

你懂的……

#2


37  

Oraculum has got it right. You shouldn't be cleaning this up on the client side. If it is clutter, then you shouldn't be sending it to client at all. Building on Oraculum's answer, you should use a custom form template because you you probably still want the hidden values in the form.

Oraculum说得对。你不应该在客户端清理。如果它是杂乱的,那么你根本不应该把它发送给客户端。基于Oraculum的答案,您应该使用自定义表单模板,因为您可能仍然需要表单中的隐藏值。

{% for field in form.visible_fields %}
    <div>
        {{ field.errors }}
        <span class="filter-label">{{ field.label_tag }}</span><br>
        {{ field }}
    </div>
 {% endfor %}

 {% for field in form.hidden_fields %}
     <div style="display:none;">{{ field }}</div>
 {% endfor %}

Using a custom form template to control hidden fields is cleaner because it doesn't send extraneous info to the client.

使用自定义表单模板来控制隐藏字段更简洁,因为它不会向客户端发送无关的信息。

#3


36  

I can't believe several people have suggested using jQuery for this...

我不敢相信有几个人建议用jQuery来解决这个问题……

Is it a case of: when the only tool you know is a hammer everything looks like a nail?

当你唯一知道的工具是锤子时,所有东西看起来都像钉子吗?

Come on, if you're going to do it from the client-side (instead of fixing the source of the problem in the back-end code) surely the right place to do it would be in CSS?

拜托,如果你要在客户端做这件事(而不是在后端代码中修复问题的根源),那么在CSS中做这件事肯定是正确的吗?

If you're in the admin site then it's a bit harder but if it's a regular page then it's easy to just omit the whole label from the form template, for example

如果你在管理网站,那就有点难了,但是如果是一个普通的页面,那么很容易忽略表单模板中的整个标签

If you're in the admin site then you could still override the as_table, as_ul, as_p methods of BaseForm (see django/forms/forms.py) in your GalleryAdminForm class to omit the label of any field where the label is blank (or == ':' as the value may be at this stage of rendering)

如果您在管理站点,那么您仍然可以在GalleryAdminForm类中重写as_table、as_ul、as_p BaseForm方法(参见django/forms/forms.py),以忽略标签为空的任何字段的标签

(...looking at lines 160-170 of forms.py it seems like Django 1.2 should properly omit the ':' if the label is blank so I guess you're on an older version?)

(…看看160-170行表单。看起来Django 1.2应该适当地省略':'如果标签是空的,那么我猜您使用的是旧版本?

#4


16  

Try

试一试

{% for field in form.visible_fields %}

{%用于表单中的字段。visible_fields % }

#5


3  

I think it's simpler to achieve the ":" label omission for HiddenInput widget by modifying class AdminField(object) in contrib/admin/helpers.py from :

我认为通过修改类AdminField(对象)来实现隐藏输入小部件的“:”标签省略更简单。py:

    if self.is_checkbox:
        classes.append(u'vCheckboxLabel')
        contents = force_unicode(escape(self.field.label))
    else:
        contents = force_unicode(escape(self.field.label)) + u':'

to :

:

    if self.is_checkbox:
        classes.append(u'vCheckboxLabel')
        contents = force_unicode(escape(self.field.label))
    else:            
        contents = force_unicode(escape(self.field.label))
        #MODIFIED 26/10/2009
        if self.field.label <> '':
           contents += u':'
        # END MODIFY

#6


3  

Check the answer at Create a hidden field in the admin site, it can be done without JavaScript by overriding admin/includes/fieldset.html From there, you can inject a CSS class, and do the rest.

在admin站点中创建一个隐藏字段时检查答案,通过覆盖admin/include /fieldset,无需JavaScript即可完成。从那里,你可以注入一个CSS类,然后做剩下的。

#7


2  

In theory, you should be able to pass label_suffix into the form constructor. However, the Django admin ignores this.

理论上,您应该能够将label_suffix传递到表单构造函数中。然而,Django admin忽略了这一点。

You've been bitten by two bugs in Django: #18134 'BoundField.label_tag should include form.label_suffix' (fixed in trunk, should be in 1.6) and to a lesser extent #11277 Hidden fields in Inlines are displayed as empty rows.

你在Django被两个bug咬了:#18134 'BoundField。label_tag应该包括形式。label_suffix'(固定在trunk中,应该在1.6中)和更小程度上,inline中的#11277隐藏字段显示为空行。

Currently, the best solution is to override the admin fieldset template. Use a HiddenInput for your widget, then override the admin fieldset template (documented here). Just create a templates/admin/includes/fieldset.html with the following contents:

目前,最好的解决方案是覆盖admin fieldset模板。为您的小部件使用HiddenInput,然后重写管理字段集模板(这里有文档记录)。创建一个模板/ admin /包括/自定义字段。html有以下内容:

<fieldset class="module aligned {{ fieldset.classes }}">
    {% if fieldset.name %}<h2>{{ fieldset.name }}</h2>{% endif %}
    {% if fieldset.description %}
        <div class="description">{{ fieldset.description|safe }}</div>
    {% endif %}
    {% for line in fieldset %}
        <div class="form-row{% if line.fields|length_is:'1' and line.errors %} errors{% endif %}{% for field in line %}{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% endfor %}">
            {% if line.fields|length_is:'1' %}{{ line.errors }}{% endif %}
            {% for field in line %}
                <div{% if not line.fields|length_is:'1' %} class="field-box{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% if not field.is_readonly and field.errors %} errors{% endif %}"{% endif %}>
                    {% if not line.fields|length_is:'1' and not field.is_readonly %}{{ field.errors }}{% endif %}
                    {% if field.is_checkbox %}
                        {{ field.field }}{{ field.label_tag }}
                    {% else %}
                        {# only show the label for visible fields #}
                        {% if not field.field.is_hidden %}
                        {{ field.label_tag }}
                        {% endif %}

                        {% if field.is_readonly %}
                            <p>{{ field.contents }}</p>
                        {% else %}
                            {{ field.field }}
                        {% endif %}
                    {% endif %}
                    {% if field.field.help_text %}
                        <p class="help">{{ field.field.help_text|safe }}</p>
                    {% endif %}
                </div>
            {% endfor %}
        </div>
    {% endfor %}
</fieldset>

#8


2  

Based upon the solution by Wilfried Hughes I 've changed the fieldset.html with little improvements.

根据Wilfried Hughes的解决方案,我已经更改了fieldset。html没有改进。

The code snippet below not only hides the input element instead if the fieldset contains only one single element which input-type is set to hidden it also hides the surrounding div-elements wasting no space in the form.

下面的代码片段不仅隐藏了输入元素,如果fieldset只包含一个将input-type设置为隐藏的元素,它还隐藏了周围的div-element,在表单中不浪费任何空间。

<fieldset class="module aligned {{ fieldset.classes }}">
{% if fieldset.name %}<h2>{{ fieldset.name }}</h2>{% endif %}
{% if fieldset.description %}
    <div class="description">{{ fieldset.description|safe }}</div>
{% endif %}
{% for line in fieldset %}
    <div class="form-row{% if line.fields|length_is:'1' and line.errors %} errors{% endif %}{% for field in line %}{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% endfor %}"{% if line.fields|length_is:'1' %}{% for field in line %}{% if field.field.is_hidden %} style="display: none"{% endif %}{% endfor %}{% endif %}>
        {% if line.fields|length_is:'1' %}{{ line.errors }}{% endif %}
        {% for field in line %}
            <div{% if not line.fields|length_is:'1' %} class="field-box{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% if not field.is_readonly and field.errors %} errors{% endif %}"{% endif %}{% if field.field.is_hidden %} style="display: none"{% endif %}>
                {% if not line.fields|length_is:'1' and not field.is_readonly %}{{ field.errors }}{% endif %}
                {% if field.is_checkbox %}
                    {{ field.field }}{{ field.label_tag }}
                {% else %}
                    {# only show the label for visible fields #}
                    {% if not field.field.is_hidden %}
                    {{ field.label_tag }}
                    {% endif %}

                    {% if field.is_readonly %}
                        <p>{{ field.contents }}</p>
                    {% else %}
                        {{ field.field }}
                    {% endif %}
                {% endif %}
                {% if field.field.help_text %}
                    <p class="help">{{ field.field.help_text|safe }}</p>
                {% endif %}
            </div>
        {% endfor %}
    </div>
{% endfor %}

#9


0  

The following removes the ':' from all your form fields. I've only tried it with the forms.Form class, but I believe it should work for forms.ModelForm too.

下面将从所有表单字段中删除':'。我只是用表格来试过。形式类,但我认为它应该适用于形式。ModelForm。

In Django forms, the ':' after the labels is the label_suffix. You can change or remove the label_suffix by creating a subclass of ModelForm, here called UnstyledForm, and redefining the initialization function with label_suffix set to an empty string. Then use your new UnstyledForm class.

在Django表单中,标签后面的':'是label_suffix。您可以通过创建ModelForm的子类(这里称为UnstyledForm)来更改或删除label_suffix,并使用设置为空字符串的label_suffix重新定义初始化函数。然后使用新的UnstyledForm类。

class UnstyledForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        kwargs.setdefault('label_suffix', '')
        super(UnstyledForm, self).__init__(*args, **kwargs)

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

I hope that helps!

我希望会有帮助!

#10


0  

Another way to do it, but i think it still better to iterate form.visible_fields & form.hidden_fields

另一种方法,但我认为迭代形式更好。visible_fields & form.hidden_fields

<form action="{% url 'some_url' param %}" method="POST">
    {% csrf_token %}
    <div class="row">
        {% for field in form %}

            {% if not field.is_hidden %}
                <div class="col-md-6">
                    {{ field.label_tag }}
                    {{ field.error }}
                    {{ field }}
                </div>
            {% else %}
                {{ field }}
            {% endif %}
        {% endfor %}
     </div>
</form>

#1


-18  

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

如果你用的是JQuery,那么就应该这样做:

Your form

表单

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

Javascript code to add to your template

添加到模板的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();
});

And add form_field_container to your template context. An example:

并将form_field_container添加到模板上下文。一个例子:

If you render your form like this:

如果你像这样呈现你的表单:

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

Your context must include:

你的上下文必须包括:

'form_field_container': 'span'

You get the idea...

你懂的……

#2


37  

Oraculum has got it right. You shouldn't be cleaning this up on the client side. If it is clutter, then you shouldn't be sending it to client at all. Building on Oraculum's answer, you should use a custom form template because you you probably still want the hidden values in the form.

Oraculum说得对。你不应该在客户端清理。如果它是杂乱的,那么你根本不应该把它发送给客户端。基于Oraculum的答案,您应该使用自定义表单模板,因为您可能仍然需要表单中的隐藏值。

{% for field in form.visible_fields %}
    <div>
        {{ field.errors }}
        <span class="filter-label">{{ field.label_tag }}</span><br>
        {{ field }}
    </div>
 {% endfor %}

 {% for field in form.hidden_fields %}
     <div style="display:none;">{{ field }}</div>
 {% endfor %}

Using a custom form template to control hidden fields is cleaner because it doesn't send extraneous info to the client.

使用自定义表单模板来控制隐藏字段更简洁,因为它不会向客户端发送无关的信息。

#3


36  

I can't believe several people have suggested using jQuery for this...

我不敢相信有几个人建议用jQuery来解决这个问题……

Is it a case of: when the only tool you know is a hammer everything looks like a nail?

当你唯一知道的工具是锤子时,所有东西看起来都像钉子吗?

Come on, if you're going to do it from the client-side (instead of fixing the source of the problem in the back-end code) surely the right place to do it would be in CSS?

拜托,如果你要在客户端做这件事(而不是在后端代码中修复问题的根源),那么在CSS中做这件事肯定是正确的吗?

If you're in the admin site then it's a bit harder but if it's a regular page then it's easy to just omit the whole label from the form template, for example

如果你在管理网站,那就有点难了,但是如果是一个普通的页面,那么很容易忽略表单模板中的整个标签

If you're in the admin site then you could still override the as_table, as_ul, as_p methods of BaseForm (see django/forms/forms.py) in your GalleryAdminForm class to omit the label of any field where the label is blank (or == ':' as the value may be at this stage of rendering)

如果您在管理站点,那么您仍然可以在GalleryAdminForm类中重写as_table、as_ul、as_p BaseForm方法(参见django/forms/forms.py),以忽略标签为空的任何字段的标签

(...looking at lines 160-170 of forms.py it seems like Django 1.2 should properly omit the ':' if the label is blank so I guess you're on an older version?)

(…看看160-170行表单。看起来Django 1.2应该适当地省略':'如果标签是空的,那么我猜您使用的是旧版本?

#4


16  

Try

试一试

{% for field in form.visible_fields %}

{%用于表单中的字段。visible_fields % }

#5


3  

I think it's simpler to achieve the ":" label omission for HiddenInput widget by modifying class AdminField(object) in contrib/admin/helpers.py from :

我认为通过修改类AdminField(对象)来实现隐藏输入小部件的“:”标签省略更简单。py:

    if self.is_checkbox:
        classes.append(u'vCheckboxLabel')
        contents = force_unicode(escape(self.field.label))
    else:
        contents = force_unicode(escape(self.field.label)) + u':'

to :

:

    if self.is_checkbox:
        classes.append(u'vCheckboxLabel')
        contents = force_unicode(escape(self.field.label))
    else:            
        contents = force_unicode(escape(self.field.label))
        #MODIFIED 26/10/2009
        if self.field.label <> '':
           contents += u':'
        # END MODIFY

#6


3  

Check the answer at Create a hidden field in the admin site, it can be done without JavaScript by overriding admin/includes/fieldset.html From there, you can inject a CSS class, and do the rest.

在admin站点中创建一个隐藏字段时检查答案,通过覆盖admin/include /fieldset,无需JavaScript即可完成。从那里,你可以注入一个CSS类,然后做剩下的。

#7


2  

In theory, you should be able to pass label_suffix into the form constructor. However, the Django admin ignores this.

理论上,您应该能够将label_suffix传递到表单构造函数中。然而,Django admin忽略了这一点。

You've been bitten by two bugs in Django: #18134 'BoundField.label_tag should include form.label_suffix' (fixed in trunk, should be in 1.6) and to a lesser extent #11277 Hidden fields in Inlines are displayed as empty rows.

你在Django被两个bug咬了:#18134 'BoundField。label_tag应该包括形式。label_suffix'(固定在trunk中,应该在1.6中)和更小程度上,inline中的#11277隐藏字段显示为空行。

Currently, the best solution is to override the admin fieldset template. Use a HiddenInput for your widget, then override the admin fieldset template (documented here). Just create a templates/admin/includes/fieldset.html with the following contents:

目前,最好的解决方案是覆盖admin fieldset模板。为您的小部件使用HiddenInput,然后重写管理字段集模板(这里有文档记录)。创建一个模板/ admin /包括/自定义字段。html有以下内容:

<fieldset class="module aligned {{ fieldset.classes }}">
    {% if fieldset.name %}<h2>{{ fieldset.name }}</h2>{% endif %}
    {% if fieldset.description %}
        <div class="description">{{ fieldset.description|safe }}</div>
    {% endif %}
    {% for line in fieldset %}
        <div class="form-row{% if line.fields|length_is:'1' and line.errors %} errors{% endif %}{% for field in line %}{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% endfor %}">
            {% if line.fields|length_is:'1' %}{{ line.errors }}{% endif %}
            {% for field in line %}
                <div{% if not line.fields|length_is:'1' %} class="field-box{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% if not field.is_readonly and field.errors %} errors{% endif %}"{% endif %}>
                    {% if not line.fields|length_is:'1' and not field.is_readonly %}{{ field.errors }}{% endif %}
                    {% if field.is_checkbox %}
                        {{ field.field }}{{ field.label_tag }}
                    {% else %}
                        {# only show the label for visible fields #}
                        {% if not field.field.is_hidden %}
                        {{ field.label_tag }}
                        {% endif %}

                        {% if field.is_readonly %}
                            <p>{{ field.contents }}</p>
                        {% else %}
                            {{ field.field }}
                        {% endif %}
                    {% endif %}
                    {% if field.field.help_text %}
                        <p class="help">{{ field.field.help_text|safe }}</p>
                    {% endif %}
                </div>
            {% endfor %}
        </div>
    {% endfor %}
</fieldset>

#8


2  

Based upon the solution by Wilfried Hughes I 've changed the fieldset.html with little improvements.

根据Wilfried Hughes的解决方案,我已经更改了fieldset。html没有改进。

The code snippet below not only hides the input element instead if the fieldset contains only one single element which input-type is set to hidden it also hides the surrounding div-elements wasting no space in the form.

下面的代码片段不仅隐藏了输入元素,如果fieldset只包含一个将input-type设置为隐藏的元素,它还隐藏了周围的div-element,在表单中不浪费任何空间。

<fieldset class="module aligned {{ fieldset.classes }}">
{% if fieldset.name %}<h2>{{ fieldset.name }}</h2>{% endif %}
{% if fieldset.description %}
    <div class="description">{{ fieldset.description|safe }}</div>
{% endif %}
{% for line in fieldset %}
    <div class="form-row{% if line.fields|length_is:'1' and line.errors %} errors{% endif %}{% for field in line %}{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% endfor %}"{% if line.fields|length_is:'1' %}{% for field in line %}{% if field.field.is_hidden %} style="display: none"{% endif %}{% endfor %}{% endif %}>
        {% if line.fields|length_is:'1' %}{{ line.errors }}{% endif %}
        {% for field in line %}
            <div{% if not line.fields|length_is:'1' %} class="field-box{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% if not field.is_readonly and field.errors %} errors{% endif %}"{% endif %}{% if field.field.is_hidden %} style="display: none"{% endif %}>
                {% if not line.fields|length_is:'1' and not field.is_readonly %}{{ field.errors }}{% endif %}
                {% if field.is_checkbox %}
                    {{ field.field }}{{ field.label_tag }}
                {% else %}
                    {# only show the label for visible fields #}
                    {% if not field.field.is_hidden %}
                    {{ field.label_tag }}
                    {% endif %}

                    {% if field.is_readonly %}
                        <p>{{ field.contents }}</p>
                    {% else %}
                        {{ field.field }}
                    {% endif %}
                {% endif %}
                {% if field.field.help_text %}
                    <p class="help">{{ field.field.help_text|safe }}</p>
                {% endif %}
            </div>
        {% endfor %}
    </div>
{% endfor %}

#9


0  

The following removes the ':' from all your form fields. I've only tried it with the forms.Form class, but I believe it should work for forms.ModelForm too.

下面将从所有表单字段中删除':'。我只是用表格来试过。形式类,但我认为它应该适用于形式。ModelForm。

In Django forms, the ':' after the labels is the label_suffix. You can change or remove the label_suffix by creating a subclass of ModelForm, here called UnstyledForm, and redefining the initialization function with label_suffix set to an empty string. Then use your new UnstyledForm class.

在Django表单中,标签后面的':'是label_suffix。您可以通过创建ModelForm的子类(这里称为UnstyledForm)来更改或删除label_suffix,并使用设置为空字符串的label_suffix重新定义初始化函数。然后使用新的UnstyledForm类。

class UnstyledForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        kwargs.setdefault('label_suffix', '')
        super(UnstyledForm, self).__init__(*args, **kwargs)

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

I hope that helps!

我希望会有帮助!

#10


0  

Another way to do it, but i think it still better to iterate form.visible_fields & form.hidden_fields

另一种方法,但我认为迭代形式更好。visible_fields & form.hidden_fields

<form action="{% url 'some_url' param %}" method="POST">
    {% csrf_token %}
    <div class="row">
        {% for field in form %}

            {% if not field.is_hidden %}
                <div class="col-md-6">
                    {{ field.label_tag }}
                    {{ field.error }}
                    {{ field }}
                </div>
            {% else %}
                {{ field }}
            {% endif %}
        {% endfor %}
     </div>
</form>