Django Widget Tweaks Implementation

Django Widget Tweaks

Hello Techies,

In this blog, we will check how to implement Django Widget Tweaks to make the form effective and user friendly with its features and django-widget-tweaks examples. So you can make your login, registration, and other templates attractive using Django Widget Tweaks.

Let’s start with django-widget-tweaks tutorial.

Table of contents

  1. Introduction
  2. Installation
  3. Django Basic Forms Rendering
  4. Django Widget Tweaks Form Rendering
  5. Django Widget Tweaks Forms Field Customization
  6. Extra features

1. Introduction (Django Widget Tweaks)

The Django Widget Tweaks is used to render form fields in templates. This allows you to adjust the properties of the form (such as method and CSS class) on the back-end without rewriting the template.


2. Installation

To install Django Widget Tweaks you need to use python package manager “pip”.

Use the below command to install Django Widget Tweaks.

pip install django-widget-tweaks

Add this application to the INSTALLED_APPS list after installation. You can check out their official site to learn more about this application and more advanced options.

INSTALLED_APPS = [
    ... #existing apps
 
    'widget_tweaks',
]

Before we move on to the implementation of the Django Widget Tweaks, we first need to explain why we need this package. Now, most of the templates come with bootstrap functionality and this is always difficult for those developers who don’t know much about the designing part. So in such cases, developers can go for the Django Widget Tweaks package.

Let’s check the basic Django form without using any third-party application.

Below code for a model.

from django.db import models

class Products(models.Model):
    class Meta:
        db_table = 'products'

    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=150)
    price = models.DecimalField(max_digits=20, decimal_places=2, 
            default = 0.0)
    category = models.CharField(max_length=150)
    description = models.TextField()


3. Django Basic Forms Rendering

Let’s check the basic form rendering without using any CSS.

The Python code to represent the product detail form is as follows.

# app/urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('basic_product/', views.BasicProductView.as_view(), name="basic_product_view"),
]
# app/views.py

from django.views.generic import CreateView
from .models import Products

class BasicProductView(CreateView):
    model = Products

    template_name = 'basic_product_view.html'
    fields = ['name', 'price', 'category', 'description']
    success_url = "/basic_product"

Template View

Create separate html (basic_product_view.html) for basic product view and add the below code in it.

{% extends 'base.html' %}
{% block content %}
  <h1>Add Product</h1>
  <form method="post" novalidate>
    {% csrf_token %}
    {{ form }}
    <button type="submit" class="btn btn-success">Save</button>
  </form>
{% endblock %}

Rendered HTML

Rendered HTML with validation


4. Django Widget Tweaks Form Rendering

We will now see how to use the Django widget tweaks in HTML.
You need to load the template tag ({% widget_tweaks %}) into the template.

Template View

{% extends 'base.html' %}
{% load widget_tweaks %}

{% block content %}
  <h1>Add Product</h1>
  <form method="post" novalidate>
    {% csrf_token %}
    {% for field in form.visible_fields %}
      <div class="form-group">
        <label for="{{ field.id_for_label }}">{{ field.label }}</label>
        {{ field|add_class:'form-control' }}
        {% for error in field.errors %}
          <span class="text-danger">{{ error }}</span>
        {% endfor %}
      </div>
    {% endfor %}
    <button type="submit" class="btn btn-success">Save</button>
  </form>
{% endblock %}

Rendered HTML

Rendered HTML with validation


5. Django Widget Tweaks Forms Field Customization

If you want to customize the form field, you can manually render the field using the form.field and the related attribute for eg. {{ form.name|add_class:”form-control”}}

Template View

{% extends 'base.html' %}
{% load widget_tweaks %}

{% block content %}
  <h1>Add Product</h1>
  <form method="post" novalidate>
    {% csrf_token %}
    <div class="row">
      <div class="col-6">
        <label for="id_name">Name</label>
        {{ form.name|add_class:"form-control"}}
        <span class="text-danger">{{ form.name.errors|striptags }}</span>
      </div>
      <div class="col-6">
        <label for="id_category">Category</label>
        {{ form.category|add_class:"form-control" }}
        <span class="text-danger">{{ form.category.errors|striptags }}</span>
      </div>
    </div>
    <br/>
    <div class="row">
      <div class="col-6">
        <label for="id_price">Price</label>
        {{ form.price|add_class:"form-control" }}
        <span class="text-danger">{{ form.price.errors|striptags }}</span>
      </div>
    </div>
    <br/>
    <div class="row">
      <div class="col-6">
        <label for="id_desc">Description</label>
        {{ form.description|add_class:"form-control" }}
        <span class="text-danger">{{ form.description.errors|striptags }}</span>
      </div>
    </div>
    <br/>
    <button type="submit" class="btn btn-success">Save</button>
  </form>
{% endblock %}

Rendered HTML

Rendered HTML with validation


6. Extra features

Add label

{{ form.name|add_label_class:"label_class_1 label_class_2" }}

Add required class

{{ form.name|add_required_class:"is-required" }}

You can also render form fields using the render_field template tag. Let’s check some example using render_fields tag.

Add class to field

{% render_field form.name class="form-control" %}

Add Placeholder to field

{% render_field form.name class="form-control" placeholder= form.name.label %}

Mixing render_field 

Using it you can mix all render field tags and filters.

{% render_field form.name|append_attr:"readonly:readonly" type="text" placeholder="Enter Name" class="form-control" %}

I hope you understand all the steps. If you have any query do comment below.

Refer a django-widget-tweaks github link for source code.

Leave a Comment