以这个非常简单的形式为例:

class SearchForm(Form):
    q = forms.CharField(label='search')

这将在模板中呈现:

<input type="text" name="q" id="id_q" />

然而,我想在这个字段中添加一个搜索值的占位符属性,这样HTML看起来就像这样:

<input type="text" name="q" id="id_q" placeholder="Search" />

最好是我想通过字典或类似的东西在表单类中传递占位符值到CharField:

q = forms.CharField(label='search', placeholder='Search')

实现这一目标的最佳方式是什么?


当前回答

class FormClass(forms.ModelForm):
    class Meta:
        model = Book
        fields = '__all__'
        widgets = {
            'field_name': forms.TextInput(attrs={'placeholder': 'Type placeholder text here..'}),
        }

其他回答

大多数时候,我只是希望所有占位符都等于在模型中定义的字段的详细名称

我添加了一个mixin,可以很容易地对我创建的任何表单进行此操作,

class ProductForm(PlaceholderMixin, ModelForm):
    class Meta:
        model = Product
        fields = ('name', 'description', 'location', 'store')

And

class PlaceholderMixin:
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        field_names = [field_name for field_name, _ in self.fields.items()]
        for field_name in field_names:
            field = self.fields.get(field_name)
            field.widget.attrs.update({'placeholder': field.label})

当您只想覆盖一个小部件的占位符时,必须知道如何实例化它是不可取的。

    q = forms.CharField(label='search')
    ...
    q.widget.attrs['placeholder'] = "Search"
class FormClass(forms.ModelForm):
    class Meta:
        model = Book
        fields = '__all__'
        widgets = {
            'field_name': forms.TextInput(attrs={'placeholder': 'Type placeholder text here..'}),
        }

您可以使用此代码为表单中的每个TextInput字段添加占位符attr。占位符的文本将取自模型字段标签。

class PlaceholderDemoForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(PlaceholderDemoForm, self).__init__(*args, **kwargs)
        for field_name in self.fields:
            field = self.fields.get(field_name)  
            if field:
                if type(field.widget) in (forms.TextInput, forms.DateInput):
                    field.widget = forms.TextInput(attrs={'placeholder': field.label})

    class Meta:
        model = DemoModel

其他方法都很好。然而,如果你不喜欢指定字段(例如对于一些动态方法),你可以使用这个:

def __init__(self, *args, **kwargs):
    super(MyForm, self).__init__(*args, **kwargs)
    self.fields['email'].widget.attrs['placeholder'] = self.fields['email'].label or 'email@address.nl'

它还允许占位符依赖于指定实例的ModelForms实例。