Ben
Ben

Reputation: 225

Django-crispy-forms: set css for individual field and inputs

Is there a way to specify the css for an individual field and input in django crispy forms? I am using bootstrap4 and would like to use a horizontal form for a few fields in my form.

I know you can use a self.helper to set label.class and field.class but I presume that applies to all field. I only want to change the label and field class on a few of my fields.

EDIT:

I need to add css to the label that is different from the input

I'm trying to get a horizontal field inside a form like the amount field below

enter image description here

<div id="div_id_amount" class="row">
    <label for="id_amount" class="col-form-label col-2  requiredField">
        Amount<span class="asteriskField">*</span>
    </label>
    <div class="">
        <input type="number" name="amount" step="0.01" class="numberinput form-control col-md" required="" id="id_amount">
        </div>
</div>

Upvotes: 1

Views: 3196

Answers (2)

dirkgroten
dirkgroten

Reputation: 20702

One solution is given here:

  • You add the class attributes for the input field via the widget, as also explained in the django docs
  • You explicitly add the <label> tags with the correct class in your HTML.

Or, for the label, you can also create the following template filter:

@register.filter(is_safe=True)
def label_with_classes(field, css):
    return field.label_tag(attrs={'class': css})

which you can use like this in your template after you've loaded it with {% load my_filters %}: {{ form.name|label_with_classes:"col-sm-6 col-lg-3" }}

I don't know of an easy way with crispy-forms.

Upvotes: 1

Andrei Pr&#227;dan
Andrei Pr&#227;dan

Reputation: 325

You can add this in your Layout:

Field('password', id="password-field", css_class="passwordfields", title="Explanation")

You can find more details here

Upvotes: 0

Related Questions