Part-13

Designing Forms In Django

When it comes to build forms, Django Forms can be really handy.It will automate a good amount of work as well as providing a really stable and secure functionality.

pic from 123RF for llustration

Django handles three distinct parts of the work involved in forms:

  1. Preparing and restructuring data to make it ready for rendering;
  2. Creating HTML forms for the data;
  3. Receiving and processing submitted forms and data from the client.

The parts 1 and 3 are usually fine for the most cases. But when it comes to the actual HTML forms rendering, sometimes it lacks some options.

In our DjangoReads project I used Bootstrap as the base for my css. and you probably know it needs some css classes for the forms elements to look good.

We rendered the form this way

<form method=’POST’ enctype=”multipart/form-data”>
{%csrf_token%}
{{u_form|crispy}}
{{p_form|crispy}}
<button type=’submit’>Update</button>
</form>

let’s try to expand one of the forms

{% for hidden in p_form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in p_form.visible_fields %}
<div class=”form-group”>
<label for=”{{ field.id_for_label }}”>{{ field.label }}</label>
{{ field }}
{% for error in field.errors %}
<span class=”help-block”>{{ error }}</span>
{% endfor %}
</div>
{% endfor %}

At this point we already added several Bootstrap elements, but our form still looks broken:

That’s where the Django Widget Tweaks takes place. We’ll use this package to add custom classes and attributes to our fields.

You can install it with pip, or download it from PyPI if you prefer:

 pip install django-widget-tweaks

Now add widget_tweaks to your INSTALLED_APPS:

INSTALLED_APPS = [
...
'widget_tweaks',
]

To start using it, you must load the template tag in the template you want to use its functions:

{% load widget_tweaks %}

Now to put Django Widget Tweaks in action, add an extra attribute to the field element:

{{ field|add_class:'form-control' }}

Or add attributes (id, type..)

{{ field|attr:"id:content" }}

Let’s use few of these django-widget-tweaks features and apply them to both the forms..

profile.html

with little bit more modifications, here’s how my profile page looks like using this package

Posting Django Tutorials with Beginner to Advanced Projects