Styling Django Forms with django-crispy-forms

Styling Django Forms with django-crispy-forms

django-crispy-forms is a popular Django application that lets you format and style Django forms with minimal effort. It supports several frontend frameworks, such as Bootstrap, Foundation, and Uni-form. Here's a guide on how to style Django forms using django-crispy-forms with Bootstrap as an example:

1. Installation:

First, install django-crispy-forms using pip:

pip install django-crispy-forms 

2. Configuration:

  • Add 'crispy_forms' to the INSTALLED_APPS in your Django project's settings:
INSTALLED_APPS = [ ... 'crispy_forms', ] 
  • Set the template pack you want to use (e.g., Bootstrap 4):
CRISPY_TEMPLATE_PACK = 'bootstrap4' 

3. Usage:

In your Django forms, you can now load the crispy_forms_tags and use the |crispy filter to style your form:

{% load crispy_forms_tags %} <form method="post"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-primary">Submit</button> </form> 

4. Advanced Usage:

  • Form Helpers: You can customize the form's rendering using Form Helpers. Here's an example:
from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit from django import forms class MyForm(forms.Form): name = forms.CharField() age = forms.IntegerField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'post' self.helper.add_input(Submit('submit', 'Submit')) 
  • Form Layouts: Use Layout objects to control the form's appearance in more detail:
from crispy_forms.layout import Layout, Fieldset, ButtonHolder, Submit self.helper.layout = Layout( Fieldset( 'Personal info', 'name', 'age' ), ButtonHolder( Submit('submit', 'Save', css_class='button white') ) ) 
  • Bootstrap Components: django-crispy-forms provides components specific to Bootstrap, such as Tab and TabHolder.

5. Overriding Global Style:

You can create a crispy_forms directory in your templates directory and override the default templates if needed.

6. Form Partials:

If you want to render only a part of the form using crispy, you can use:

{% with form.my_field as field %} {% crispy_field field %} {% endwith %} 

This is useful when manually laying out forms but wanting to maintain the crispy appearance for individual fields.

In essence, django-crispy-forms provides an easy way to add professional styling to your Django forms with very little effort. It's a powerful tool, especially when combined with frontend frameworks like Bootstrap.


More Tags

loader filtering tablet text-widget opencv3.0 model-binding maven-nar-plugin webpack-2 svg-android angular-material2

More Programming Guides

Other Guides

More Programming Examples