在django-crispy-forms中使用字段标签作为占位符

时间:2012-11-20 21:46:06

标签: django twitter-bootstrap django-crispy-forms

我正在考虑使用DRY方式为我的<input> HTML元素的占位符属性使用字段标签。我正在使用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)

但是,我不希望单独设置标签和占位符,因为这最终会有更多字段,而且非常详细。

你有什么建议?

7 个答案:

答案 0 :(得分:14)

使用 __ 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

答案 1 :(得分:5)

目前,可以使用下面的bootstrap helper attribute隐藏标签:

  

self.helper.form_show_labels = False

     

默认设置为True。它决定是否渲染或不形成字段标签。

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

  

字段(&#39;查询&#39;,占位符=&#39;搜索...&#39;),

答案 2 :(得分: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)

答案 3 :(得分:1)

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

query = CharField(widget=forms.TextInput(attrs={'placeholder':'Search..'}),
                  max_length=50, label='', required=False)

答案 4 :(得分:0)

此DRY解决方案不需要修改布局。我建议把它变成混合物:

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)

答案 5 :(得分: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']

答案 6 :(得分:-1)

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