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.
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.