Modifying HTML with Django ModelForm
May 14, 2010
Sometimes you need to modify the HTML produced for a Django Model Form, for example to specify the number of columns to show in a TextArea.
Starting from a simple form:
from django import forms class XmlClassForm(forms.ModelForm): class Meta: model = XmlClass fields = ('name','maps_to','maintainable','description')
This uses the defaults for all the fields. To modify, simply re-declare the field and specify the widget with options:
class XmlClassForm(forms.ModelForm): name = forms.CharField(widget=forms.TextInput(attrs={'size':50})) maps_to = forms.CharField(required=False, widget=forms.TextInput(attrs={'size':50})) description = forms.CharField(widget=forms.Textarea(attrs={'cols': 130, 'rows': 10})) class Meta: model = XmlClass fields = ('name','maps_to','maintainable','description')