1

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?

Jamie Bull
  • 12,889
  • 15
  • 77
  • 116

3 Answers3

1

Set the widget's placeholder attribute:

form = VerbTestForm()
form.fields['answer'].widget.attrs['placeholder'] = tip.tip
catavaran
  • 44,703
  • 8
  • 98
  • 85
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:

AlvaroAV
  • 10,335
  • 12
  • 60
  • 91
1

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()
Fanis Despoudis
  • 362
  • 1
  • 7