crispy forms

Date: April 12th 2016
Last updated: April 12th 2016

Crispy forms is an add-on App that requires installation first. After installing, crispy forms provides a helper function (i.e. forms.py) to format layout. The gotcha for me was that I hadn't added the CRISPY_TEMPLATE_PACK in settings.py and nothing was happening. The self.helper.label_class and self.helper.field_class in forms.py can have a wide variety of bootstrap options. Just remember that the page layout is based on a 12 column grid system.

Useful resources

install (command line)

sudo pip3 install --upgrade django-crispy-forms

update settings.py

INSTALLED_APPS = [
    ...
    'crispy_forms',
    ...
    ]

# My form layout was not working until 
#I added this to the bottom of settings.py
CRISPY_TEMPLATE_PACK = 'bootstrap3'

forms.py (example using Add board form)

# add crispy modules
from crispy_forms.helper import FormHelper
from django.core.urlresolvers import reverse_lazy
from crispy_forms.layout import Submit


class BoardForm(forms.ModelForm):
    class Meta:
        model = Board
        fields = ['boardmake',
                    'boardtail',
                    'boardlength',
                    #<- snipped ->
                    ]

    def __init__(self, *args, **kwargs):
        super(BoardForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_method = 'post' # this line sets your form's method to post
        self.helper.form_class = 'form-horizontal'
        #self.helper.form_show_labels = False #<-- uncomment to suppress labels
        self.helper.label_class = 'col-lg-4'
        self.helper.field_class = 'col-lg-6'
        self.helper.add_input(Submit('submit', u'Submit'))

addboard.html

  1. load crispy_forms_tags (A)
  2. Add crispy tag before 'form' (B)
{% extends 'surferprofile/base.html' %}

<!-- base includes link to styles.css -->

{% block title_block %} Add boards {% endblock %}
{% load crispy_forms_tags %} <!-- A --->

{% block body_block %}
<div id = "formcontainer">
  <h1 style="text-align: center;">Add a new board</h1>

  {% if user.id == surfer.user.id %}
  <form id='addboard' role="form" action="" method="post" style="text-align: right;">
      {% csrf_token %}
      {% crispy form %} <!-- B --->
  </form>
</div>

  {% else %}
  {% endif %}

{% endblock %}

styles.css

#formcontainer{
    width: 600px;
    margin: auto;
    font-family: oswald;
    margin-top: 3%;

output

results matching ""

    No results matching ""