有人知道是否有正确的方法去除脆皮上的标签吗?
我到目前为止:
self.fields['field'].label = ""
但这不是一个很好的解决方案。
就这样做:
self.helper.form_show_labels = False
删除所有标签。
与 Boostrap 配合使用(参见文档)
在您的表格中:
from crispy_forms.helper import FormHelper
from django import forms
class MyForm(forms.Form):
[...]
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_show_labels = False
在您的模板中:
<form method='POST' action=''>{% csrf_token %}
{% crispy form %}
<input type='submit' value='Submit' class='btn btn-default'>
</form>
您可以编辑
field.html
模板:
https://github.com/maraujop/django-crispy-forms/blob/dev/crispy_forms/templates/bootstrap/field.html#L7
向表单添加一个
FormHelper
属性来控制标签呈现,并在该模板中使用它 if
。自定义 FormHelper
属性尚未正式记录,因为我没有时间,但我在主题演讲中讨论了它们,以下是幻灯片:
https://speakerdeck.com/u/maraujop/p/django-crispy-forms
下面的解决方案可让您从常规或脆皮控件中删除标签。不仅标签文本消失,标签使用的空间也被删除,这样您就不会出现空白标签占用空间并弄乱布局的情况。
下面的代码适用于 django 2.1.1。
# this class would go in forms.py
class SectionForm(forms.ModelForm):
# add a custom field for calculation if desired
txt01 = forms.CharField(required=False)
def __init__(self, *args, **kwargs):
''' remove any labels here if desired
'''
super(SectionForm, self).__init__(*args, **kwargs)
# remove the label of a non-linked/calculated field (txt01 added at top of form)
self.fields['txt01'].label = ''
# you can also remove labels of built-in model properties
self.fields['name'].label = ''
class Meta:
model = Section
fields = "__all__"
我不清楚OP所展示的代码片段有什么问题,只是他没有将代码行放在正确的位置。这似乎是最好和最简单的解决方案。
如果您只想从输入中删除一些标签,则明确不要在模型定义中给出标签名称,即:
field = models.IntegerField("",null=True)
删除所有标签:
self.helper.form_show_labels = False
显示特定标签当全部为False时:
HTML('<span>Your Label</span>')
禁用特定字段的标签 当所有内容均为 True 时
self.fields['fieldName'].label = True
示例:
Row(
HTML('<span> Upolad Government ID (Adhar/PAN/Driving Licence)</span>'),
Column('IdProof',css_class='form-group col-md-12 mb-0'),
css_class='form-row'
),
通过这种方式,您可以从字段中删除标签,或更改默认标签文本。
class ModelNameForm(forms.ModelForm):
class Meta:
model = OfferResidential
fields = ['field_with_label', 'field_no_label']
# all field mentioned here, with value '' will be shown without label
labels = {
'field_no_label': '',
}