Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Crispy Forms: Set rows for Text Area

When creating a Form with FormHelper(), the text areas of my form (for TextFields) are too big: They are set to 10 rows. I'd like to set the number of rows. How can I do that?

My code:

models.py:

from django.db import models

class Spam(models.Model).
    ham = models.CharField(max_length=10, blank=True, null=False, default='Some ham')
    eggs = models.TextField(blank=True, null=False, default='', verbose_name="Lots of eggs")

forms.py:

from django import forms
from crispy_forms.helper import FormHelper
from crispyy_forms.layout import (Layout, Row, Column)

from .models import Spam

class SpamForm(forms.ModelForm):
    class Meta():
        model = Spam
        fields = ('ham', 'eggs')
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_method = 'POST'
        self.helper.layout = Layout(
            Row(Column('ham', css_class='form-group col-12')),
            Row(Column('eggs', css_class='form-group col-12')),
            # HERE: How can I set the rows for the text area widget?
        )

Resulting HTML:

<!-- (ommited for brevity)  -->
<div  class="form-row " > 
  <div class="form_group col-12"  rows="2">
    <div id="div_id_eggs" class="form-group">
      <label for="eggs" class="">Lots of eggs</label> 
      <div class=""> 
          <textarea name="eggs" cols="40" rows="10" class="textarea form-control" id="eggs"></textarea> 
          <!--                            ^^^^^^^^
          <!--                            THIS is what I'd like to change to "2" -->
      </div>
    </div> 
  </div>
</div>
<!-- (ommited for brevity)  -->
like image 704
Barranka Avatar asked Jan 25 '23 18:01

Barranka


2 Answers

You need to alter the attributes for the TextArea widget that your eggs field is using.

class SpamForm(forms.ModelForm):
    # no changes here
    
    def __init__(self, *args, **kwargs):
        # No changes to your existing code, just add this:
        self.fields['eggs'].widget.attrs = {'rows': 2}
like image 147
YellowShark Avatar answered Feb 05 '23 04:02

YellowShark


You can "override" the rows directly with crispy forms by passing rows in:

Row(Column('eggs', rows='2', css_class='form-group col-12')),

or with field:

Field('eggs', rows='2')
like image 39
Keaton Avatar answered Feb 05 '23 05:02

Keaton