- Django forms html class
- CSS classes and Django form fields
- The Problem
- The Solution(s)
- Using a form widget attribute
- Using django-floppyforms
- Using django-widget-tweaks
- The add_class template filter
- The render_field template tag
- Conclusion
- Comments
- Write Pythonic code
- Favorite Posts
- How to add class and other attributes to django form fields
- 1. Add form-control class to all fields using for loop.
- 2. Add form-control class to a specific field.
- 3. Add other attributes to form fields.
- Related Articles.
Django forms html 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:
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.
How to add class and other attributes to django form fields
Take your Django forms to the next level by adding custom classes and attributes. Our simple guide shows you how to easily add extra styles to enhance the look of your forms. Try it out now!
In this tutorial, we will learn how to add CSS class attributes (like form-control), placeholders, IDs, and other attributes in your Django forms.
Let’s create a Product Model:
# models.py from django.db import models class Product(models.Model): title = models.CharField( null=False, blank=False, max_length=25, validators=[validate_amazing] ) slug = models.CharField(unique=True, max_length=20) quantity = models.PositiveIntegerField() price = models.DecimalField(max_digits=5, decimal_places=2) def __str__(self): return self.title
1. Add form-control class to all fields using for loop.
Now let’s write a code to create ProductForm and add CSS class and placeholder attribute.
# forms.py from django import forms from .models import Product class ProductForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for visible in self.visible_fields(): visible.field.widget.attrs['class'] = 'form-control' visible.field.widget.attrs['placeholder'] = visible.field.label class Meta: model = Product fields = '__all__'
The __init__ method sets the class attribute of each field’s widget to ‘form-control’ and the placeholder attribute to the field’s label. This allows for easy styling of the form using Bootstrap CSS and also sets the placeholder text for each field to the field’s label.
When this form is rendered in a template, each field in the form will have the form-control class and its placeholder text will be the field’s label.
In the above code, we are using for loop to add the class and placeholder attribute to all visible fields. But what if you want to add class and placeholder attribute to a specific field, not all fields? Then this is how you can do this.
2. Add form-control class to a specific field.
# forms.py from django import forms from .models import Product class ProductForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['title'].widget.attrs['class'] = 'form-control' self.fields['title'].widget.attrs['placeholder'] = 'Write product title here' class Meta: model = Product fields = '__all__'
Here we are adding the class and placeholder to the specific field » title «.
3. Add other attributes to form fields.
You can also add different attributes like ID, data-* attributes, etc to form fields.
# forms.py from django import forms from .models import Product class ProductForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for visible in self.visible_fields(): visible.field.widget.attrs['class'] = 'form-control' visible.field.widget.attrs['placeholder'] = visible.field.label # new self.fields['price'].widget.attrs['id'] = 'price' self.fields['price'].widget.attrs['data-discount'] = '10%' class Meta: model = Product fields = '__all__'
That’s it. If you find it useful then show some love and support by clapping or by buying me coffee. And don’t forget to share it with your friends. In case of any problem, you can comment here or you can also directly approach me through my LinkedIn.
Related Articles.
I would greatly appreciate it if you subscribe to my YouTube channel, Let’s Code More