Maddie Graham
Maddie Graham

Reputation: 2177

Using crispy in Django to change the field size

I have a very simple form for my template. I would like to change its size.

enter image description here

How can you do this? by adding a widget in my forms.py file or by adding a certain class in my template?

My template:

              <form method="POST">
                {% csrf_token %}
                <div class="form-row">
                  <div class="form-group col-md-12 mb-0">
                    {{ basic_form.choices_product|as_crispy_field }}
                  </div>
                </div>
                <button type="submit" class="btn btn-lg btn-block btn-danger">Wyszukaj <i class="fas fa-heart fa-lg"></i></button>
              </form>

I was looking for information on the internet, but to no avail.

I use Bootstrap 4, Django 2+.

Upvotes: 1

Views: 2449

Answers (1)

Max Zia
Max Zia

Reputation: 78

When your template is evaluated, the variable specified between your {{ ... }} will be replaced with an "input" element in the HTML DOM. You want to render this "input" element with the Bootstrap 4 class "form-control-lg" or a style attribute such as "line-height", which will change height of the element.

crispy-forms allows you to do all this from forms.py

Specifically, you can change the way form fields are rendered with crispy-forms by using the Layout class from the crispy_forms.layout module. Full details are given here in the crispy-forms docs.

In your case, you would need to (1) Add a FormHelper to your form; (2) Add a layout to your helper; and (3) Use the Field layout object to set attributes on any field.

So you can change forms.py like so:

from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Field

from django import forms

class BasicForm(forms.Form):
     [...] # Define your fields here
     def__init__(self, *args, **kwargs):
            # Add a FormHelper
            self.helper = FormHelper()
            # Add a layout to your helper
            self.helper.layout = Layout(
                # Use the Field layout object to set attributes on 
                # choices_product field. type="text" should be there by
                # default if you have used a CharField or TextField.
                Field(
                    'choices_product', css_class="form-control form-control-lg", id="exampleInputSize3", placeholder=".form-control-lg",
                )
            )
        super(BasicForm, self).__init__(*args, **kwargs)

Upvotes: 2

Related Questions