DEV Community

tdvr
tdvr

Posted on

1

Easy way to customize Django Forms

Cover photo, before and after

A quick and simple overview to Bootstrap and style your Django forms.

I had to go through this recently. I read many threads and comments around asking the same questions, so I guess a simple thread wouldn't be bad for anyone who just starts using Django.

1. Install django-widget-tweaks and Bootstrap.

You can install it through pip:

$ pip install django-widget-tweaks


2. Import Bootstrap and django-widget-tweaks.

Open the settings.py of your Django project, find INSTALLED_APPS and insert widget_tweaks there.

Image description

To import Bootstrap, just visit the official page, click Get Started and copy the stylesheet <link> into your <head> of your base.html which is used for template extending in Django.

Image description


3. Load widget_tweaks to your template.

Insert {% load widget_tweaks %} to your template.

Image description


4. Use render_field template tag

A render_field template tag provides the ability to customize any form field easily with HTML attributes and CSS classes. The complete list of features appear on the official repository of the package

{% render_field form.username class="form-control" placeholder="Username" %}
    ...
    ...
{% render_field form.password2 class="form-control" id="PassConf" placeholder="Confirm Password" %}
Enter fullscreen mode Exit fullscreen mode

5 Some CSS to style your forms as you please.

.form-control{
    border: 1px solid rgba(65, 65, 65, 0.91);
    box-shadow: 0 0 0 0.15rem rgba(0, 0, 0, 0.25);
}
.form-control:hover {
    border: 1px solid rgb(184, 69, 241);
    box-shadow: 0 0 0 0.25rem rgba(192, 112, 246, 0.64);
}

.form-control:focus {
    border: 1px solid rgb(0, 127, 244, 1);
    box-shadow: 0 0 0 0.25rem rgb(0, 127, 244, 0.45);
}

#PassConf {
    border: 1px solid rgb(92, 241, 69);
    box-shadow: 0 0 0 0.2rem rgba(112, 246, 166, 0.64);
}
Enter fullscreen mode Exit fullscreen mode

Source code and all the customization options: https://github.com/jazzband/django-widget-tweaks/

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs