• Stars
    star
    2,019
  • Rank 22,018 (Top 0.5 %)
  • Language
    Python
  • License
    MIT License
  • Created about 12 years ago
  • Updated 6 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Tweak the form field rendering in templates, not in python-level form definitions. CSS classes and HTML attributes can be altered.

django-widget-tweaks

Jazzband PyPI Version GitHub Actions Coverage

Tweak the form field rendering in templates, not in python-level form definitions. Altering CSS classes and HTML attributes is supported.

That should be enough for designers to customize field presentation (using CSS and unobtrusive javascript) without touching python code.

License is MIT.

Installation

You can get Django Widget Tweaks by using pip:

$ pip install django-widget-tweaks

To enable widget_tweaks in your project you need to add it to INSTALLED_APPS in your projects settings.py file:

INSTALLED_APPS += [
    'widget_tweaks',
]

Usage

This app provides two sets of tools that may be used together or standalone:

  1. a render_field template tag for customizing form fields by using an HTML-like syntax.
  2. several template filters for customizing form field HTML attributes and CSS classes

The render_field tag should be easier to use and should make form field customizations much easier for designers and front-end developers.

The template filters are more powerful than the render_field tag, but they use a more complex and less HTML-like syntax.

render_field

This is a template tag that can be used as an alternative to aforementioned filters. This template tag renders a field using a syntax similar to plain HTML attributes.

Example:

{% load widget_tweaks %}

<!-- change input type (e.g. to HTML5) -->
{% render_field form.search_query type="search" %}

<!-- add/change several attributes -->
{% render_field form.text rows="20" cols="20" title="Hello, world!" %}

<!-- append to an attribute -->
{% render_field form.title class+="css_class_1 css_class_2" %}

<!-- template variables can be used as attribute values -->
{% render_field form.text placeholder=form.text.label %}

<!-- double colon -->
{% render_field form.search_query v-bind::class="{active:isActive}" %}

For fields rendered with {% render_field %} tag it is possible to set error class and required fields class by using WIDGET_ERROR_CLASS and WIDGET_REQUIRED_CLASS template variables:

{% with WIDGET_ERROR_CLASS='my_error' WIDGET_REQUIRED_CLASS='my_required' %}
    {% render_field form.field1 %}
    {% render_field form.field2 %}
    {% render_field form.field3 %}
{% endwith %}

You can be creative with these variables: e.g. a context processor could set a default CSS error class on all fields rendered by {% render_field %}.

attr

Adds or replaces any single html attribute for the form field.

Examples:

{% load widget_tweaks %}

<!-- change input type (e.g. to HTML5) -->
{{ form.search_query|attr:"type:search" }}

<!-- add/change several attributes -->
{{ form.text|attr:"rows:20"|attr:"cols:20"|attr:"title:Hello, world!" }}

<!-- attributes without parameters -->
{{ form.search_query|attr:"autofocus" }}


<!-- attributes with double colon Vuejs output: v-bind:class="{active:ValueEnabled}" -->
{{ form.search_query|attr:"v-bind::class:{active:ValueEnabled}" }}

add_class

Adds CSS class to field element. Split classes by whitespace in order to add several classes at once.

Example:

{% load widget_tweaks %}

<!-- add 2 extra css classes to field element -->
{{ form.title|add_class:"css_class_1 css_class_2" }}

set_data

Sets HTML5 data attribute ( http://ejohn.org/blog/html-5-data-attributes/ ). Useful for unobtrusive javascript. It is just a shortcut for 'attr' filter that prepends attribute names with 'data-' string.

Example:

{% load widget_tweaks %}

<!-- data-filters:"OverText" will be added to input field -->
{{ form.title|set_data:"filters:OverText" }}

append_attr

Appends attribute value with extra data.

Example:

{% load widget_tweaks %}

<!-- add 2 extra css classes to field element -->
{{ form.title|append_attr:"class:css_class_1 css_class_2" }}

'add_class' filter is just a shortcut for 'append_attr' filter that adds values to the 'class' attribute.

remove_attr

Removes any single html attribute for the form field.

Example:

{% load widget_tweaks %}

<!-- removes autofocus attribute from field element -->
{{ form.title|remove_attr:"autofocus" }}

add_label_class

The same as add_class but adds css class to form labels.

Example:

{% load widget_tweaks %}

<!-- add 2 extra css classes to field label element -->
{{ form.title|add_label_class:"label_class_1 label_class_2" }}

add_error_class

The same as 'add_class' but adds css class only if validation failed for the field (field.errors is not empty).

Example:

{% load widget_tweaks %}

<!-- add 'error-border' css class on field error -->
{{ form.title|add_error_class:"error-border" }}

add_error_attr

The same as 'attr' but sets an attribute only if validation failed for the field (field.errors is not empty). This can be useful when dealing with accessibility:

{% load widget_tweaks %}

<!-- add aria-invalid="true" attribute on field error -->
{{ form.title|add_error_attr:"aria-invalid:true" }}

add_required_class

The same as 'add_error_class' adds css class only for required field.

Example:

{% load widget_tweaks %}

<!-- add 'is-required' css class on field required -->
{{ form.title|add_required_class:"is-required" }}

field_type and widget_type

'field_type' and 'widget_type' are template filters that return field class name and field widget class name (in lower case).

Example:

{% load widget_tweaks %}

<div class="field {{ field|field_type }} {{ field|widget_type }} {{ field.html_name }}">
    {{ field }}
</div>

Output:

<div class="field charfield textinput name">
    <input id="id_name" type="text" name="name" maxlength="100" />
</div>

Mixing render_field and filters

The render_field tag and filters mentioned above can be mixed.

Example:

{% render_field form.category|append_attr:"readonly:readonly" type="text" placeholder="Category" %}

returns:

<input name="category" placeholder="Profession" readonly="readonly" type="text">

Filter chaining

The order django-widget-tweaks filters apply may seem counter-intuitive (leftmost filter wins):

{{ form.simple|attr:"foo:bar"|attr:"foo:baz" }}

returns:

<input foo="bar" type="text" name="simple" id="id_simple" />

It is not a bug, it is a feature that enables creating reusable templates with overridable defaults.

Reusable field template example:

{# inc/field.html #}
{% load widget_tweaks %}
<div>{{ field|attr:"foo:default_foo" }}</div>

Example usage:

{# my_template.html #}
{% load widget_tweaks %}
<form method='POST' action=''> {% csrf_token %}
    {% include "inc/field.html" with field=form.title %}
    {% include "inc/field.html" with field=form.description|attr:"foo:non_default_foo" %}
</form>

With 'rightmost filter wins' rule it wouldn't be possible to override |attr:"foo:default_foo" in main template.

Contributing

If you've found a bug, implemented a feature or have a suggestion, do not hesitate to contact me, fire an issue or send a pull request.

Testing

Make sure you have tox installed, then type

tox

from the source checkout.

NOT SUPPORTED

MultiWidgets: SplitDateTimeWidget, SplitHiddenDateTimeWidget

More Repositories

1

django-debug-toolbar

A configurable set of panels that display various debug information about the current request/response.
Python
7,858
star
2

pip-tools

A set of tools to keep your pinned Python dependencies fresh.
Python
7,398
star
3

tablib

Python Module for Tabular Datasets in XLS, CSV, JSON, YAML, &c.
Python
4,500
star
4

django-silk

Silky smooth profiling for Django
Python
4,210
star
5

djangorestframework-simplejwt

A JSON Web Token authentication plugin for the Django REST Framework.
Python
3,765
star
6

django-taggit

Simple tagging for django
Python
3,205
star
7

django-oauth-toolkit

OAuth2 goodies for the Djangonauts!
Python
3,021
star
8

django-redis

Full featured redis cache backend for Django.
Python
2,773
star
9

django-model-utils

Django model mixins and utilities.
Python
2,577
star
10

django-push-notifications

Send push notifications to mobile devices through GCM or APNS in Django.
Python
2,210
star
11

django-simple-history

Store model history and view/revert changes from admin site.
Python
2,083
star
12

sorl-thumbnail

Thumbnails for Django
Python
1,717
star
13

django-constance

Dynamic Django settings.
Python
1,643
star
14

django-two-factor-auth

Complete Two-Factor Authentication for Django providing the easiest integration into most Django projects.
Python
1,590
star
15

django-polymorphic

Improved Django model inheritance with automatic downcasting
Python
1,577
star
16

django-pipeline

Pipeline is an asset packaging library for Django.
Python
1,489
star
17

dj-database-url

Use Database URLs in your Django Application.
Python
1,439
star
18

django-axes

Keep track of failed login attempts in Django-powered sites.
Python
1,356
star
19

django-tinymce

TinyMCE integration for Django
JavaScript
1,231
star
20

prettytable

Display tabular data in a visually appealing ASCII table format
Python
1,223
star
21

django-admin2

Extendable, adaptable rewrite of django.contrib.admin
Python
1,182
star
22

django-analytical

Analytics services for Django projects
Python
1,174
star
23

django-smart-selects

chained and grouped selects for django forms
Python
1,094
star
24

django-waffle

A feature flipper for Django
Python
1,075
star
25

django-configurations

A helper for organizing Django project settings by relying on well established programming patterns.
Python
1,067
star
26

django-rest-knox

Authentication Module for django rest auth
Python
1,057
star
27

django-defender

A simple super fast django reusable app that blocks people from brute forcing login attempts
Python
997
star
28

django-auditlog

A Django app that keeps a log of changes made to an object.
Python
990
star
29

django-payments

Universal payment handling for Django.
Python
964
star
30

django-hosts

Dynamic and static host resolving for Django. Maps hostnames to URLconfs.
Python
942
star
31

django-nose

Django test runner using nose
Python
882
star
32

django-dbbackup

Management commands to help backup and restore your project database and media files
Python
879
star
33

geojson

Python bindings and utilities for GeoJSON
Python
876
star
34

django-floppyforms

Full control of form rendering in the templates.
Python
836
star
35

django-newsletter

An email newsletter application for the Django web application framework, including an extended admin interface, web (un)subscription, dynamic e-mail templates, an archive and HTML email support.
Python
825
star
36

django-avatar

A Django app for handling user avatars.
Python
797
star
37

django-formtools

A set of high-level abstractions for Django forms
Python
735
star
38

django-user-sessions

Extend Django sessions with a foreign key back to the user, allowing enumerating all user's sessions.
Python
586
star
39

django-admin-sortable

Generic drag-and-drop ordering for objects and tabular inlines in Django Admin
Python
557
star
40

django-invitations

Generic invitations app for Django
Python
530
star
41

django-sortedm2m

A transparent sorted ManyToMany field for django.
Python
508
star
42

django-recurrence

Utility for working with recurring dates in Django.
Python
460
star
43

django-categories

This app attempts to provide a generic category system that multiple apps could use. It uses MPTT for the tree storage and provides a custom admin for better visualization (copied and modified from feinCMS).
Python
455
star
44

django-robots

A Django app for managing robots.txt files following the robots exclusion protocol
Python
451
star
45

django-embed-video

Django app for easy embedding YouTube and Vimeo videos and music from SoundCloud.
Python
383
star
46

wagtailmenus

An app to help you manage and render menus in your Wagtail projects more effectively
Python
380
star
47

django-downloadview

Serve files with Django.
Python
357
star
48

jsonmodels

jsonmodels is library to make it easier for you to deal with structures that are converted to, or read from JSON.
Python
328
star
49

django-queued-storage

Provides a proxy for Django storage backends that allows you to upload files locally and eventually serve them remotely
Python
314
star
50

django-permission

[Not maintained] An enhanced permission system which support object permission in Django
Python
302
star
51

django-eav2

Django EAV 2 - EAV storage for modern Django
Python
297
star
52

django-revproxy

Reverse Proxy view that supports all HTTP methods, Diazo transformations and Single Sign-On.
Python
290
star
53

django-authority

A Django app that provides generic per-object-permissions for Django's auth app and helpers to create custom permission checks.
Python
286
star
54

django-simple-menu

Simple, yet powerful, code-based menus for Django applications
Python
258
star
55

django-dbtemplates

Django template loader for database stored templates with extensible cache backend
JavaScript
250
star
56

django-mongonaut

Built from scratch to replicate some of the Django admin functionality and add some more, to serve as an introspective interface for Django and Mongo.
Python
240
star
57

django-fsm-log

Automatic logging for Django FSM
Python
235
star
58

django-cookie-consent

Reusable application for managing various cookies and visitors consent for their use in Django project.
Python
210
star
59

django-celery-monitor

Celery Monitoring for Django
Python
191
star
60

django-ddp

Django/PostgreSQL implementation of the Meteor server.
Python
167
star
61

icalevents

Python module for iCal URL/file parsing and querying.
Python
153
star
62

docopt-ng

Humane command line arguments parser. Now with maintenance, typehints, and complete test coverage.
Python
149
star
63

django-voting

A generic voting application for Django
Python
93
star
64

django-ical

iCal feeds for Django based on Django's syndication feed framework.
Python
89
star
65

django-flatblocks

django-chunks + headerfield + variable chunknames + "inclusion tag" == django-flatblocks
Python
82
star
66

django-redshift-backend

Redshift database backend for Django
Python
80
star
67

pathlib2

Backport of pathlib aiming to support the full stdlib Python API.
Python
80
star
68

website

Code for the Jazzband website
Python
63
star
69

django-sorter

A helper app for sorting objects in Django templates.
Python
53
star
70

django-discover-jenkins

A streamlined fork of django-jenkins designed to work with the default test command and the discover runner
Python
49
star
71

contextlib2

contextlib2 is a backport of the standard library's contextlib module to earlier Python versions.
Python
37
star
72

django-fernet-encrypted-fields

Python
35
star
73

imaplib2

Fork of Piers Lauder's imaplib2 library for Python.
Python
31
star
74

help

Use this repo to get help from the roadies
27
star
75

.github

Community health and config files for Jazzband
7
star
76

django-postgres-utils

Django app providing additional lookups and functions for PostgreSQL
Python
7
star
77

admin

Some admin files for Jazzband
3
star
78

actions

Various GitHub actions for Jazzband projects
1
star