CSS classes and Django form fields
Django forms provide input validation and HTML form field generation. They also integrate nicely with models. However, Django itself does not allow one-off customizations of form-generated HTML.
In this post I will discuss a method for customizing the HTML generated by Django form fields, with the specific goal of adding custom CSS classes to Django form fields.
Here’s a Django form definition:
from django import forms class AuthenticationForm(forms.Form): username = forms.CharField(max_length=254) password = forms.CharField(widget=forms.PasswordInput)
Here’s the form used in a template:
The Problem
We’re using Bootstrap and we want to add an input-lg CSS class onto our username field to make it really big.
The Solution(s)
There are many ways to solve this problem. I will discuss some solutions I dislike before I discuss my preferred solution.
Using a form widget attribute
We could add a class attribute to our Django form field:
from django import forms class AuthenticationForm(forms.Form): username = forms.CharField( max_length=254, widget=forms.TextInput(attrs='class': "input-lg">), ) password = forms.CharField(widget=forms.PasswordInput)
I dislike this approach because it requires including presentation rules in our back-end code. This class attribute is used exclusively by our CSS and/or JavaScript and should therefore live in Django templates, not in Python code.
Using django-floppyforms
If we’re using django-floppyforms we could include logic in our floppyforms/attrs.html template to add specific classes based on a context variable (example). Here’s an example:
This should work but it’s ugly and in general I do not enjoy maintaining heavy logic in my templates.
Aside: there is currently an open issue on django-floppyforms discussing how this could be added as a feature to the library.
Using django-widget-tweaks
I prefer to solve this problem with django-widget-tweaks.
The django-widget-tweaks library provides two solutions to this problem:
The add_class template filter
Mikhail Korobov originally created the django-widget-tweaks library in 2011. It started as a series of template filters for modifying form field attributes from your Django templates.
Here’s an example usage of the add_class filter for adding a CSS class to our form field:
I find this solution both easy to read and easy to maintain.
The render_field template tag
I discovered django-widget-tweaks shortly after Mikhail created it. I appreciated his solution for this problem, but I wanted a more HTML-like syntax for my form field customizations. I created the render_field template tag to satisfy that desire.
With the render_field tag you can add attributes to form fields with a much more HTML-like syntax:
As a bonus, with render_field we can also set a CSS class for erroneous and required form fields. See the documentation for more details.
Conclusion
I have not had a chance to use django-floppyforms yet, but I expect that django-widget-tweaks and django-floppyforms would integrate well together.
I am on the lookout for new solutions to this problem, but django-widget-tweaks has served me well so far. I have used it for three years now it remains one of my go-to libraries for new Django projects.
How do you add CSS classes do your Django form fields? If you have another solution please leave a comment below.
Posted by Trey Hunner Sep 30 th , 2014 11:00 am django, python
Comments
Hi! My name is Trey Hunner.
I help Python teams write better Python code through Python team training.
I also help individuals level-up their Python skills with weekly Python skill-building.
Write Pythonic code
The best way to improve your skills is to write more code, but it’s time consuming to figure out what code to write. I’ve made a Python skill-building service to help solve this problem.
Each week you’ll get an exercise that’ll help you dive deeper into Python and carefully reflect on your own coding style. The first 3 exercises are free.
Sign up below for three free exercises!
Favorite Posts
Copyright © 2023 — Trey Hunner — Powered by Octopress
Need to fill-in gaps in your Python skills? I send regular emails designed to do just that.
You’re nearly signed up. You just need to check your email and click the link there to set your password.
Right after you’ve set your password you’ll receive your first Python Morsels exercise.
Django form css class
Поля формы применяют некоторые стили по умолчанию. Если же мы хотим применить к ним какие-то собственные стили и классы, то нам надо использовать ряд механизмов.
Прежде всего мы можем вручную выводить каждое поле и определять правила стилизации для этого поля или окружающих его блоков. Возьмем простейшую форму:
from django import forms class UserForm(forms.Form): name = forms.CharField(min_length=3) age = forms.IntegerField(min_value=1, max_value=100)
В шаблоне пропишем ее использование:
.alert .form-group .form-group input>>>Результа при отправке формы с ошибками:
Второй механизм представляют свойства формы required_css_class и error_css_class , который соответственно применяют класс css к метке, создаваемой для поля формы, и к блоку ассоциированных с ним ошибок.
Например, определим следующую форму:
from django import forms class UserForm(forms.Form): name = forms.CharField(min_length=3) age = forms.IntegerField(min_value=1, max_value=100) required_css_class = "field" error_css_class = "error"В этом случае в шаблоне у нас должны быть определены или подключены классы «field» и «error»:
Но также можно было бы комбинировать оба способа:
Третий механизм стилизации представляет установка классов и стилей через виджеты:
from django import forms class UserForm(forms.Form): name = forms.CharField(widget=forms.TextInput(attrs=)) age = forms.IntegerField(widget=forms.NumberInput(attrs=))В данном случае через параметр виджетов attrs устанавливаются атрибуты того элемента html, который будет генерироваться. В частности, здесь для обоих полей устанавливается атрибут class , который представляет класс myfield.
И, допустим, в шаблоне будет определен класс myfield: