When creating a Form with FormHelper()
, the text areas of my form (for TextField
s) 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?
)
<!-- (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) -->
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}
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With