找到你要的答案

Q:Setting an example answer in a text input field

Q:在文本输入字段中设置示例答案

I'm trying to set a default value in a text input field which gives the user an example of what to enter. This should be greyed-out and should disappear as soon as they start typing. I've tried setting an initial value but this isn't automatically replaced when the user starts to type and is formatted the same as the user-entered answer.

form = VerbTestForm(initial={'answer': tip.tip})

What do I need to pass to my form to get the behaviour I'm looking for?

我试图在文本输入字段中设置默认值,这给用户输入了一个示例。这应该是灰色的,当他们开始打字消失。我尝试设置一个初始值,但当用户开始键入并格式化与用户输入的答案相同时,这不会自动被替换。

form = VerbTestForm(initial={'answer': tip.tip})

我需要通过什么来获得我想要的行为?

answer1: 回答1:

You are setting an initial value but you're looking for a placeholder.

You should try something like this:

class VerbTestForm(forms.ModelForm):
    # Your code ...
    class Meta:
        # Your code ...

        widgets = {
            'answer': forms.TextInput(attrs={'placeholder': tip.tip}),
        }

or you can add the placeholder after defining the form like:

form = VerbTestForm()
form.fields['answer'].widget.attrs['placeholder'] = tip.tip

The official documentation is quite well explained, you should check:

你设定一个初始值,但是你要找一个占位符。

你应该试试这样的东西:

class VerbTestForm(forms.ModelForm):
    # Your code ...
    class Meta:
        # Your code ...

        widgets = {
            'answer': forms.TextInput(attrs={'placeholder': tip.tip}),
        }

或者你可以在定义形式如添加占位符:

form = VerbTestForm()
form.fields['answer'].widget.attrs['placeholder'] = tip.tip

官方文件是很好的解释,你应该检查:

answer2: 回答2:

Set the widget's placeholder attribute:

form = VerbTestForm()
form.fields['answer'].widget.attrs['placeholder'] = tip.tip

设置控件的占位符属性:

form = VerbTestForm()
form.fields['answer'].widget.attrs['placeholder'] = tip.tip
answer3: 回答3:

A widget placeholder is your answer:

 class VerbTestForm(forms.Form):
     answer = forms.CharField(widget=forms.TextInput(attrs={'placeholder': tip.tip}))

you can quickly test the generated HTML by calling the as_p or as_table methods

>>> f = VerbTestForm(auto_id=False)
>>> f.as_table()

一个插件占位符是你的答案:

 class VerbTestForm(forms.Form):
     answer = forms.CharField(widget=forms.TextInput(attrs={'placeholder': tip.tip}))

你可以很快的测试生成的调用方法as_p或as_table HTML

>>> f = VerbTestForm(auto_id=False)
>>> f.as_table()
python  django  django-forms