Ben Ripkens

back to blog index

Adding custom attributes to Form fields / widgets

Currently I’m learning Python and Django by creating a web application. My goal is to learn as much as possible and to create a web application that adheres to as many code guidelines as possible.

Today I wanted to create a form from a model. With Django you would normally use a ModelForm. Unfortunately this approach is to generic for my desired form. That’s why I’m creating a subclass of django.forms.Form. Applying the DRY principle I still don’t want to rewrite all the validation logic / constraints which are already part of the model. You can use the fields_from_model function from django.forms.models which does exactly that. It creates form fields for each model field. Thus you don’t need to place the validation logic in two places.

from django import forms
from django.forms.models import fields_for_model
from models import Pattern

class ManagePattern(forms.Form):
    _pattern_fields = fields_for_model(Pattern)
    name = _pattern_fields['name']

Django automatically creates the input fields based on the form fields. In this case name will be an instance of django.forms.CharField. Later on this would be rendered as an HTML input element with type=”text”.

To add attributes to this element you need to add the attributes to the widget of the form field. In this case I wanted to add the new HTML 5 autofocus attribute.

from django import forms
from django.forms.models import fields_for_model
from models import Pattern

class ManagePattern(forms.Form):
    _pattern_fields = fields_for_model(Pattern)
    name = _pattern_fields['name']
    name.widget.attrs.update({'autofocus' : 'autofocus'})
That's me, Ben.
Hey, I am Ben Ripkens (bripkens) and this is my blog. I live in Düsseldorf (Germany) and I am employed by the codecentric AG as a Software Engineer. Web application frontends are my main area of expertise, but you may also find some other interesting articles on this blog.