Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 851
Alex Avatar asked Mar 24 '16 22:03

Alex


2 Answers

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.

like image 151
YPCrumble Avatar answered Nov 14 '22 10:11

YPCrumble


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

CRISPY_TEMPLATE_PACK = 'bootstrap4'
like image 2
jaco Avatar answered Nov 14 '22 11:11

jaco