Exercise - Implement django-crispy-forms

Completed

After you view the created form, you might notice that the formatting isn't the same as the rest of our page. We're using Bootstrap, and the form currently isn't. Fortunately, there's a library that can ensure our forms use Bootstrap too.

The django-crispy-forms library

The django-crispy-forms library further enhances how forms are generated by Django. We're going to explore how we can use the library to ensure our forms use Bootstrap.

Install the library

As with any Python library, we install django-crispy-forms by using pip.

  1. Inside Visual Studio Code, open requirements.txt.

  2. At the bottom of the file, add a new line that reads:

    django-crispy-forms
    
  3. Open a new terminal window by selecting Terminal > New Terminal.

  4. Install all packages by running the following command:

    pip install -r requirements.txt
    

Register the app in Django and configure the template

Anything Django uses must be registered as an app or middleware. Because django-crispy-forms is an app, we'll list it in the INSTALLED_APPS list.

  1. Inside Visual Studio Code, open project/settings.py.

  2. Underneath the line that reads # TODO: Register crispy_forms, add the following code to register django-crispy-forms.

    # TODO: Register crispy_forms
    'crispy_forms',
    
  3. Underneath the line that reads # TODO: Set template_pack, add the following code to configure django-crispy-forms to use Bootstrap 4.

    # TODO: Set template_pack
    CRISPY_TEMPLATE_PACK = 'bootstrap4'
    

Update our template to use django-crispy-forms

The bulk of the amazing work that django-crispy-forms does is by using a filter. A filter allows you to take a variable in a template and pass it into another handler or process. In our case, the crispy filter will convert our form to the specified template, Bootstrap 4.

  1. Inside Visual Studio Code, open dog_shelters/templates/dog_form.html.

  2. Underneath the line that reads {# TODO: Load crispy_forms_tags #}, add the following code to load the filter or tag.

    {# TODO: Load crispy_forms_tags #}
    {% load crispy_forms_tags %}
    
  3. Replace the line that reads {{ form.as_p }} with the following code to use the crispy filter.

    {{ form | crispy }}
    

Test the site

With everything installed and updated, let's test our site.

  1. Save all files by selecting File > Save All.

  2. In your browser, go to http://localhost:8000/dog/register.

    You'll see the page is now using Bootstrap for the form.

    Screenshot of the form that uses Bootstrap.

You've now updated your application so that the form uses Bootstrap.