I have the following form:
开发者_如何学运维from django import forms
class PostForm(forms.Form):
message = forms.CharField(widget=forms.Textarea)
and the following part in my template
<p>{{ form.message }}</p>
it renders the field as a textarea as specified. Though for the template I want to set it to 4 rows and 25 cols without actually touching the form definiton. Is that possible?
class PostForm(forms.Form):
message = forms.CharField(widget=forms.Textarea)
def set4x25(self):
self.fields['message'].widget.attrs = {'rows':'4', 'cols': '25'}
And in template:
{{ form.set4x25 }}
{{ form.message }}
You can customize this idea as you like.
You can do it in template with django-widget-tweaks:
{% load widget_tweaks %}
<p>{% render_field form.message rows="4" cols="25" %}</p>
or
{% load widget_tweaks %}
<p>{{ form.message|attr:"rows:4"|attr:"cols:25" }}</p>
You can't do it from the template but you can:
Use CSS to specify the width and height of the textarea. This will override rows and cols attributes
Render the field manually:
{% with form.message as field %} <textarea name="{{ field.html_name }}" id="{{ field.html_initial_id }}" rows="4" cols="25">{% if field.data %}{{ field.data }}{% endif %}</textarea> {% endfor %}
精彩评论