13

我有一个自定义表单,它创建一个字段的隐藏输入:

class MPForm( forms.ModelForm ):
    def __init__( self, *args, **kwargs ):
        super(MPForm, self).__init__( *args, **kwargs )
        self.fields['mp_e'].label = "" #the trick :)

class Meta:
    model = MeasurementPoint
    widgets = { 'mp_e': forms.HiddenInput()  }
    exclude = ('mp_order') 

我必须做这个小技巧来“隐藏”标签,但我想做的是将它从表单中删除。我创建这样的表格:

forms.MPForm()
4

7 回答 7

23

我不建议删除标签,因为它会使表单无法访问。您可以将自定义 CSS 类添加到该字段,并在您的 CSS中使该类不可见

编辑

我错过了输入是隐藏的,所以可访问性不是问题。

您可以直接在模板中呈现表单字段:

<form ...>
    {% for field in form.hidden_fields %}
        {{ field }}
    {% endfor %}

    {% for field in form.visible_fields %}
        {{ field.label }} {{ field }}
    {% endfor %}
</form>
于 2012-09-26T09:58:20.667 回答
14

现在,(我的django版本是2.1.4),可以这样解决->编辑forms.py文件:

password = forms.CharField(label=False)
于 2019-02-15T06:46:58.680 回答
7

如果您使用form.as_porform.as_table方法,Django 无论如何都不应该显示隐藏字段的标签,因此无需更改__init__方法中的标签。

{{ form.as_table }}

如果您正在自定义表单模板,您可以使用该field.is_hidden属性来检查该字段是否隐藏。

{% if field.is_hidden %}
   {# Don't render label #}
{% endif %}

或者,您可以分别循环隐藏和可见字段,并省略隐藏字段的标签。

于 2012-09-26T10:24:31.433 回答
4

你需要给 False ,它会起作用:

self.fields['mp_e'].label = False

django版本:2.2

于 2019-07-03T10:56:47.360 回答
2

我发现这很有用,对我有用!

class CustomForm(forms.Form):
class Meta:
    ...  #other properties such as model, fields, widgets and help text
    labels = {
       'comment' : '',
    }
于 2021-06-07T13:09:18.983 回答
1

转到您的 forms.py 文件并添加 label = false

如下

name = forms.CharField(required=True, max_length=100, widget=forms.TextInput(attrs={'placeholder': 'Enter Name *'}), label=False)
于 2019-02-25T18:36:53.070 回答
0

除非我误解了您的问题,否则您只需将 mp_e 字段添加到元类下的排除元组中。这不是你需要的吗?

class MPForm( forms.ModelForm ):
    def __init__( self, *args, **kwargs ):
        super(MPForm, self).__init__( *args, **kwargs )

    class Meta:
        model = MeasurementPoint
        exclude = ('mp_order','mp_e')  
于 2012-09-26T10:06:45.593 回答