开发者

How to add attrs to Widget at rendertime

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:

  1. Use CSS to specify the width and height of the textarea. This will override rows and cols attributes

  2. 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 %}
    
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜