[Django]-How to add attrs to Widget at rendertime

5👍

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.

2👍

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>

0👍

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 %}
    

Leave a comment