Tai
Tai

Reputation: 167

How to add help_text to display as input value?

I would like to get the help_text declared in my form class to render inside the HTML form element rather than Django's default, which displays it as a separate element. Specifically, for textarea fields the help_text would need to go between the opening and closing HTML tags and for input fields the help_text would need to be set as the value= attribute -- basically, turning:

text = forms.CharField(widget=forms.Textarea(attrs={'class':'form-control', 'rows':2}), help_text="Some help text")
image = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}), help_text="More help text")

into:

<textarea class="form-control" id="id_text" name="text" rows="2">Some help text</textarea>
<input class="form-control" id="id_image" name="image" value="More help text">

As is, the first block of code does not insert the help_text anywhere.

One way to do it would be to just use template tags to insert everything inline, but this feels like a hack.

<textarea class="form-control" id="{{ form.text.auto_id }}" name="{{ form.text.html_name }}" rows="2">{{ form.text.help_text }}</textarea>
<input class="form-control" id="{{ form.image.auto_id }}" name="{{ form.image.html_name }}" value="{{ form.image.help_text }}">

I figure there's gotta be a better way?

Upvotes: 0

Views: 1873

Answers (2)

user14539908
user14539908

Reputation: 11

This answer might be too late...but for others who may need.

If for instance, you got a model field name job_summary, then you may do this in your forms.py:

class JobForm(forms.Form):
    model = Job
...
    class Meta:
        widgets = {'job_summary', forms.Textarea(attrs={'placeholder': Job._meta.get_field('job_summary').help_text}), }

Upvotes: 1

Aswin Murugesh
Aswin Murugesh

Reputation: 11070

Instead of using the help_text, use placeholder attribute.

text = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Some help text'}))

Upvotes: 1

Related Questions