7

我正在考虑将字段标签用于我的<input>HTML 元素的占位符属性的 DRY 方式。我正在使用django-crispy-forms.

现在我有:

class FilterForm(Form):

    query = CharField(max_length=50, label='', required=False)

    def __init__(self, data=None, files=None, **kwargs):
        self.helper = FormHelper()
        self.helper.layout = Layout(
            Field('query', placeholder='Search ...'),
        )
        super(FilterForm, self).__init__(data, files, **kwargs)

但是,我宁愿不必分别设置标签和占位符,因为这 for 最终会有更多字段,而且非常冗长。

你有什么建议?

4

7 回答 7

20

使用此__init__方法可以实现 DRY 解决方案:

def __init__(self, *args, **kwargs):
    super(FilterForm, self).__init__(*args, **kwargs)
    helper = self.helper = FormHelper()

    # Moving field labels into placeholders
    layout = helper.layout = Layout()
    for field_name, field in self.fields.items():
        layout.append(Field(field_name, placeholder=field.label))
    helper.form_show_labels = False
于 2014-05-31T15:30:09.453 回答
5

目前,隐藏标签可以通过使用下面的引导辅助属性来实现:

self.helper.form_show_labels = False

默认设置为真。它决定是否呈现表单的字段标签。

您仍然需要使用 Field 布局对象定义占位符:

Field('查询', placeholder='搜索...'),

于 2014-04-22T12:46:11.250 回答
4

试试这个:

class FilterForm(Form):

    query = CharField(max_length=50, label='', required=False)

    def __init__(self, data=None, files=None, **kwargs):
        self.helper = FormHelper()
        self.helper.layout = Layout(
            Field('query', placeholder=kwargs.pop('query_placeholder', 'random text')),
        )
        super(FilterForm, self).__init__(data, files, **kwargs)
于 2013-06-17T11:44:10.990 回答
2

这种 DRY 解决方案不需要修改布局。我建议把它做成一个mixin:

class MyForm(Form):

    _placeholders = {
        'fieldname': 'fieldname placeholder',
    }

    def __init__(self, *args, **kwargs):

        # Assign placeholder to widget of fields
        # listed in self._placeholders.
        for field_name, field in self.fields.items():
            if field_name in self._placeholders:
                self.fields[field_name].widget.attrs['placeholder'] = \
                self._placeholders[field_name]

        super(MyForm, self).__init__(*args, **kwargs)
于 2016-03-21T18:54:05.557 回答
1

您可以使用以下方法向表单字段添加额外的属性:

query = CharField(widget=forms.TextInput(attrs={'placeholder':'Search..'}),
                  max_length=50, label='', required=False)
于 2012-11-20T23:02:59.663 回答
0

如果您想要更多控制权,可以使用小部件字段

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        widgets = {
            'comment': forms.Textarea(attrs={'rows': 6, 'placeholder': 'Enter your comments'}),
        }
        labels = {
            "private": "Keep Private",
        }
        exclude = ['response', 'display']
于 2018-06-13T14:57:36.733 回答
-1

我最终只是使用 css 隐藏了字段标签。这有点hackish,但有效。我仍然使用 placeholder="your label" 来定义占位符。

于 2013-04-18T17:33:59.740 回答