MultiWidgets and templates in Django
MultiValueFields and MultiWidgets are easy to use for making simple combined inputs such as two adjacent text boxes, but what if the data needs more than just multiple inputs strung together? Text, for example, will often be necessary to describe the function of each input.
Templates can be used for custom inputs just as they’re used everywhere else in Django. In a MultiWidget, override the format_output method to provide the HTML. The method receives an array of the rendered inputs in the same order that they were specified when created.
Here’s a simple example that I used to create a changelog:
[toggle code]
-
class CMSChangeWidget(forms.MultiWidget):
-
def __init__(self):
- widgets = (forms.HiddenInput(), forms.TextInput(), forms.Textarea())
- super(CMSChangeWidget, self).__init__(widgets)
-
def decompress(self, value):
- return value
-
def format_output(self, rendered_widgets):
- widgetContext = {'ID': rendered_widgets[0], 'title': rendered_widgets[1], 'summary': rendered_widgets[2]}
- return render_to_string("edit/parts/changelog.html", widgetContext)
-
def __init__(self):
This widget will have a hidden field for the changelog entry’s ID, an input of type “text” for the title of the change, and a textarea for a description of the change.
It can be used in a MultiValueField like this:
[toggle code]
-
class CMSChangeFields(forms.MultiValueField):
-
def __init__(self):
- fields=(forms.CharField(max_length=4, label="ID"), forms.CharField(max_length=48, label="Change"), forms.CharField(max_length=400, label="Summary"))
- widgets = CMSChangeWidget()
- super(CMSChangeFields, self).__init__(fields, widget=widgets, required=False)
-
def compress(self, data_list):
- return data_list
-
def __init__(self):
Don’t forget to include “from django.template.loader import render_to_string” to get the render_to_string function from Django.
In response to Django forms and edit_inline models: Getting edit_inline models to show up on custom forms isn’t as hard as it looks. MultiValueField and MultiWidget aren’t documented well, but they do work. Here’s how I did it in Django 0.96.
More Django
- Django: fix_ampersands and abbreviations
- Custom managers for Django ForeignKeys
- Fixing Django 1.2.4’s SuspiciousOperation on filtering
- Reusing Django’s filter_horizontal
- Django formsets and date/time fields
- 25 more pages with the topic Django, and other related pages
