Alex
Alex

Reputation: 81

Cannot display label and field on same line using django-crispy forms

I'm trying to place the label of my fields on the left side of the form with the right side having the text input. However, I can't seem to make it work. Here are the settings i've placed.

forms.py

helper = FormHelper()
helper.form_class = 'form-horizontal'
helper.layout = Layout(
    Field('test_field'),
    FormActions(
        Submit('submit', 'Record', css_class='btn btn-primary'),
        Reset('reset', 'Clear', css_class='btn btn-default'),
    )
)

form.html

{% extends 'base.html' %}
{% load crispy_forms_tags %}

{% block page_panel %}
{% crispy form %}
{% endblock %}

The resulting html is like this result

Upvotes: 8

Views: 4994

Answers (3)

vinkomlacic
vinkomlacic

Reputation: 1879

What worked for me with django-crispy-forms was using the helper attribute form_style = 'inline'.

Upvotes: 0

jaco
jaco

Reputation: 544

I couldn't get it to work either until I added the following to the settings.py:

CRISPY_TEMPLATE_PACK = 'bootstrap4'

Upvotes: 2

YPCrumble
YPCrumble

Reputation: 28662

In your example you're trying to implement a Bootstrap form-horizontal. To do this correctly you need to add helper classes to the label and form input per the docs.

Try this to make form-horizontal work, for instance:

helper = FormHelper()
helper.form_class = 'form-horizontal'
helper.label_class = 'col-lg-2'
helper.field_class = 'col-lg-8'
helper.layout = Layout(
    Field('test_field'),
    FormActions(
        Submit('submit', 'Record', css_class='btn btn-primary'),
        Reset('reset', 'Clear', css_class='btn btn-default'),
    )
)

You can adjust your column sizes as necessary.

Another option for a slightly different layout (also with label at the same level as the input vs. above it) would be to use Bootstrap's form-inline which would require different config using Django crispy forms.

Upvotes: 5

Related Questions