Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
django-crispy-forms bootstrap form example
# -*- coding: utf-8 -*-
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Div, Submit, HTML, Button, Row, Field
from crispy_forms.bootstrap import AppendedText, PrependedText, FormActions
class MessageForm(forms.Form):
text_input = forms.CharField()
textarea = forms.CharField(
widget = forms.Textarea(),
)
radio_buttons = forms.ChoiceField(
choices = (
('option_one', "Option one is this and that be sure to include why it's great"),
('option_two', "Option two can is something else and selecting it will deselect option one")
),
widget = forms.RadioSelect,
initial = 'option_two',
)
checkboxes = forms.MultipleChoiceField(
choices = (
('option_one', "Option one is this and that be sure to include why it's great"),
('option_two', 'Option two can also be checked and included in form results'),
('option_three', 'Option three can yes, you guessed it also be checked and included in form results')
),
initial = 'option_one',
widget = forms.CheckboxSelectMultiple,
help_text = "<strong>Note:</strong> Labels surround all the options for much larger click areas and a more usable form.",
)
appended_text = forms.CharField(
help_text = "Here's more help text"
)
prepended_text = forms.CharField()
prepended_text_two = forms.CharField()
multicolon_select = forms.MultipleChoiceField(
choices = (('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5')),
)
# Uni-form
helper = FormHelper()
helper.form_class = 'form-horizontal'
helper.layout = Layout(
Field('text_input', css_class='input-xlarge'),
Field('textarea', rows="3", css_class='input-xlarge'),
'radio_buttons',
Field('checkboxes', style="background: #FAFAFA; padding: 10px;"),
AppendedText('appended_text', '.00'),
PrependedText('prepended_text', '<input type="checkbox" checked="checked" value="" id="" name="">', active=True),
PrependedText('prepended_text_two', '@'),
'multicolon_select',
FormActions(
Submit('save_changes', 'Save changes', css_class="btn-primary"),
Submit('cancel', 'Cancel'),
)
)
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
{% crispy form %}
{% endblock %}
# -*- coding: utf-8 -*-
from django.shortcuts import render
from forms import MessageForm
def index(request):
# This view is missing all form handling logic for simplicity of the example
return render(request, 'index.html', {'form': MessageForm()})
@nbensa

This comment has been minimized.

Show comment Hide comment
@nbensa

nbensa Mar 23, 2013

Hello.

Is it possible to use Button('cancel', 'Cancel') in FormActions to redirect to another view?

Without crispy, I use this in my templates:

<a class="btn" href="{{ object.get_absolute_url }}">Cancel</a>

But crispy's Button() generates a <input type="button" class="btn" value="Cancel"> which in my case doesn't nothing*. An Submit() generates a <input type="submit"..... which then generate errors in the form because the form goes to the view, the view tries to validate the form, etc., etc. (I'm using class based views).

Is the only way using HTML()?

Thanks!

  • Of course, maybe I'm doing something wrong :-/

nbensa commented Mar 23, 2013

Hello.

Is it possible to use Button('cancel', 'Cancel') in FormActions to redirect to another view?

Without crispy, I use this in my templates:

<a class="btn" href="{{ object.get_absolute_url }}">Cancel</a>

But crispy's Button() generates a <input type="button" class="btn" value="Cancel"> which in my case doesn't nothing*. An Submit() generates a <input type="submit"..... which then generate errors in the form because the form goes to the view, the view tries to validate the form, etc., etc. (I'm using class based views).

Is the only way using HTML()?

Thanks!

  • Of course, maybe I'm doing something wrong :-/
@rh0dium

This comment has been minimized.

Show comment Hide comment
@rh0dium

rh0dium May 27, 2013

This is what I ended up doing.

        cancel_url = reverse('<object>:list')
        if self.instance:
            cancel_url = reverse('<object>:view', kwargs={'pk': self.instance.id})

        self.helper.layout = Layout(
            ButtonHolder(
                Submit('submit', 'Submit'),
                Button('cancel', 'Cancel', onclick='window.location.href="{}"'.format(cancel_url))
            )
        )

rh0dium commented May 27, 2013

This is what I ended up doing.

        cancel_url = reverse('<object>:list')
        if self.instance:
            cancel_url = reverse('<object>:view', kwargs={'pk': self.instance.id})

        self.helper.layout = Layout(
            ButtonHolder(
                Submit('submit', 'Submit'),
                Button('cancel', 'Cancel', onclick='window.location.href="{}"'.format(cancel_url))
            )
        )
@torabisu

This comment has been minimized.

Show comment Hide comment
@torabisu

torabisu May 30, 2013

Button('cancel', 'Cancel', onclick='history.go(-1);')

Button('cancel', 'Cancel', onclick='history.go(-1);')

@spapas

This comment has been minimized.

Show comment Hide comment
@spapas

spapas Jun 17, 2013

I instead use this to create a cancel button:

HTML("a class='btn' href='{% url \"cancel_url\" %}'>Cancel")

spapas commented Jun 17, 2013

I instead use this to create a cancel button:

HTML("a class='btn' href='{% url \"cancel_url\" %}'>Cancel")
@ldgarcia

This comment has been minimized.

Show comment Hide comment
@ldgarcia

ldgarcia Aug 6, 2013

Is there a way to leave CSS formatting on the template side?

ldgarcia commented Aug 6, 2013

Is there a way to leave CSS formatting on the template side?

@flyingfoxlee

This comment has been minimized.

Show comment Hide comment
@flyingfoxlee

flyingfoxlee Mar 17, 2014

what is in your base.html?

what is in your base.html?

@flyingfoxlee

This comment has been minimized.

Show comment Hide comment
@flyingfoxlee

flyingfoxlee Mar 17, 2014

I use crispy_forms with html5-boilerplate and bootstrap3, got the result as follow
screen

The right and left side of the rendered page exceeds the boundary of the browser.
Zoom in or zoom out won't help.
Also, it seems that it treat the web browser as a mobile one. In fact, it's on laptop.

I use crispy_forms with html5-boilerplate and bootstrap3, got the result as follow
screen

The right and left side of the rendered page exceeds the boundary of the browser.
Zoom in or zoom out won't help.
Also, it seems that it treat the web browser as a mobile one. In fact, it's on laptop.

@flyingfoxlee

This comment has been minimized.

Show comment Hide comment
@flyingfoxlee

flyingfoxlee Mar 18, 2014

I get this right by wrapping the form in a container div. Thank you for this great app.

I get this right by wrapping the form in a container div. Thank you for this great app.

@adrienbrunet

This comment has been minimized.

Show comment Hide comment
@adrienbrunet

adrienbrunet Apr 28, 2014

@flyingfoxlee Have you tried replace container by container-fluid?

@flyingfoxlee Have you tried replace container by container-fluid?

@slackmart

This comment has been minimized.

Show comment Hide comment
@slackmart

slackmart Apr 30, 2014

This is cool, thanks so much!

This is cool, thanks so much!

@zinonas

This comment has been minimized.

Show comment Hide comment
@zinonas

zinonas Aug 27, 2014

Which is that 'base.html'?

What is its path?

Thank you in advance!

zinonas commented Aug 27, 2014

Which is that 'base.html'?

What is its path?

Thank you in advance!

@daniel-milinski

This comment has been minimized.

Show comment Hide comment
@daniel-milinski

daniel-milinski Feb 15, 2015

Dosen't work

Dosen't work

@daniel-milinski

This comment has been minimized.

Show comment Hide comment
@daniel-milinski

daniel-milinski Feb 15, 2015

init() got an unexpected keyword argument 'instance' ERROR

init() got an unexpected keyword argument 'instance' ERROR

@bedros

This comment has been minimized.

Show comment Hide comment
@bedros

bedros Jul 25, 2015

thanks for the example, it helped me solve some issues with my form, but I still got couple more.

is there a way to use chosen with AppendedText like

This works

AppendedText('user','a link to add a new user')

but this one does not work

AppendedText(Field('user', css_class='chosen'),'a link to add a new user')

the form displays chosen JS autofill but it does not show the link

bedros commented Jul 25, 2015

thanks for the example, it helped me solve some issues with my form, but I still got couple more.

is there a way to use chosen with AppendedText like

This works

AppendedText('user','a link to add a new user')

but this one does not work

AppendedText(Field('user', css_class='chosen'),'a link to add a new user')

the form displays chosen JS autofill but it does not show the link

@sureshvv

This comment has been minimized.

Show comment Hide comment
@sureshvv

sureshvv Feb 11, 2016

  1. What is the role of helper.class = 'form-horizontal'?
  2. My form does not appear like a 2 column table, as in this example. What am I missing?
  1. What is the role of helper.class = 'form-horizontal'?
  2. My form does not appear like a 2 column table, as in this example. What am I missing?
@wtfrank

This comment has been minimized.

Show comment Hide comment
@wtfrank

wtfrank Jun 11, 2016

@sureshvv form-horizontal is from bootstrap I think

wtfrank commented Jun 11, 2016

@sureshvv form-horizontal is from bootstrap I think

@saiftheboss7

This comment has been minimized.

Show comment Hide comment
@saiftheboss7

saiftheboss7 Nov 7, 2016

ImportError: No module named 'forms'

What to do?

ImportError: No module named 'forms'

What to do?

@mihirsevak

This comment has been minimized.

Show comment Hide comment
@mihirsevak

mihirsevak Dec 22, 2016

How can i display radio buttons horizontally instead of vertically?? Same for the checkboxes. Can you show syntax for that in helper class?

Thanks.

How can i display radio buttons horizontally instead of vertically?? Same for the checkboxes. Can you show syntax for that in helper class?

Thanks.

@mihirsevak

This comment has been minimized.

Show comment Hide comment
@mihirsevak

mihirsevak Dec 23, 2016

Guys, I tried using inline as explained in documentation but it had no effect on the outcome. Below is my code. can someone help me identify what I am doing wrong?? Thanks.

helper = FormHelper()
helper.form_class = 'form-horizontal'                                                                                              
helper.layout = Layout(
    Field('text_input', css_class='input-xlarge'),
    Field('textarea', rows="3", css_class='input-xlarge'),                                                                         
    'radio_buttons',
    InlineRadios('radio_buttons'),
    Field('checkboxes', style="background: #FAFAFA; padding: 10px;"),                                                              
    InlineCheckboxes('checkboxes'),
    AppendedText('appended_text', '.00'),
    PrependedText('prepended_text', '<input type="checkbox" checked="checked" value="" id="" name="">', active=True),              
    PrependedText('prepended_text_two', '@'),                                                                                      
    'multicolon_select',                                                                                                           
    FormActions(
        Submit('save_changes', 'Save changes', css_class="btn-primary"),                                                           
        Submit('cancel', 'Cancel'),                                                                                                
    )                                                                                                                              
)  

Guys, I tried using inline as explained in documentation but it had no effect on the outcome. Below is my code. can someone help me identify what I am doing wrong?? Thanks.

helper = FormHelper()
helper.form_class = 'form-horizontal'                                                                                              
helper.layout = Layout(
    Field('text_input', css_class='input-xlarge'),
    Field('textarea', rows="3", css_class='input-xlarge'),                                                                         
    'radio_buttons',
    InlineRadios('radio_buttons'),
    Field('checkboxes', style="background: #FAFAFA; padding: 10px;"),                                                              
    InlineCheckboxes('checkboxes'),
    AppendedText('appended_text', '.00'),
    PrependedText('prepended_text', '<input type="checkbox" checked="checked" value="" id="" name="">', active=True),              
    PrependedText('prepended_text_two', '@'),                                                                                      
    'multicolon_select',                                                                                                           
    FormActions(
        Submit('save_changes', 'Save changes', css_class="btn-primary"),                                                           
        Submit('cancel', 'Cancel'),                                                                                                
    )                                                                                                                              
)  
@Nabot

This comment has been minimized.

Show comment Hide comment
@Nabot

Nabot May 27, 2017

Hi.. Nice tutorial. Is there a way to output the submitted results on the same page when one clicks save changes, in form of a table?

Thank you in advance.

Nabot commented May 27, 2017

Hi.. Nice tutorial. Is there a way to output the submitted results on the same page when one clicks save changes, in form of a table?

Thank you in advance.

@Kiodaddy

This comment has been minimized.

Show comment Hide comment
@Kiodaddy

Kiodaddy Jun 20, 2017

OP you saved my life by sharing this codes.

OP you saved my life by sharing this codes.

@GraniteConsultingReviews

This comment has been minimized.

Show comment Hide comment
@GraniteConsultingReviews

GraniteConsultingReviews Aug 29, 2017

Thanks for this code its working perfectly

Thanks for this code its working perfectly

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment