Time to be crisp

It can get tiresome when writing so much boilerplate for each form in your templates. The django-crispy-forms package makes the form template code more crisp (that is, concise). It moves all the presentation and layout into the Django form itself. This way, you can write more Python code and less HTML.

The following table shows that the crispy form template tag generates a more complete form, and the appearance is much more native to the Bootstrap style:

Template

Code

Output in Browser

{% crispy form %}

<form method="post">   
<input type='hidden'   name='csrfmiddlewaretoken' value='...' />   
<div id="div_id_name"   class="form-group">   
<label for="id_name"   class="control-label  requiredField">   
Name<span   class="asteriskField">*</span></label>   
<div class="controls   ">   
<input   class="textinput textInput form-control form-control" id="id_name" maxlength="100"   name="name" type="text" /> </div></div> ...   

(HTML truncated for brevity)

So, how do you get crisper forms? You will need to install the django-crispy-forms package and add it to your INSTALLED_APPS. If you use Bootstrap 4, then you will need to mention this in your settings:

CRISPY_TEMPLATE_PACK = "bootstrap4" 

The form initialization will need to mention a helper attribute of the FormHelper type. The following code in formschapter/forms.py is intended to be minimal and uses the default layout:

from crispy_forms.helper import FormHelper 
from crispy_forms.layout import Submit 
 
class PersonDetailsForm(forms.Form): 
    name = forms.CharField(max_length=100) 
    age = forms.IntegerField() 
 
    def __init__(self, *args, **kwargs): 
        super().__init__(*args, **kwargs) 
        self.helper = FormHelper(self) 
        self.helper.layout.append(Submit('submit', 'Submit')) 

For more details, read the django-crispy-forms package documentation.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.156.250