A MultiWidget is a widget that contains more than one widget and bundles it into one. Sometimes you require two or more inputs from the user where the data is not mutually exclusive. For example the expiry date on a credit card or a phone number with the area code.
This blog post will show and explain how to create a MultiWidget for an expiry date that accepts a month and a year.
Creating a MultiWidget is similar to creating a custom Widget. Here is the code for an expiry date multiwidget that accepts two values the month and year that a credit card expires.
from django.forms import TextInput, MultiWidget
class ExpiryDateWidget(MultiWidget):
def __init__(self, attrs={}):
_widgets = (
TextInput(attrs=attrs),
TextInput(attrs=attrs)
)
super(ExpiryDateWidget, self).__init__(_widgets, attrs)
def decompress(self, value):
return [value.month, value.year] if value else [None, None]
- We're creating a subclass and overiding the init method
- We then create a tuple of Widgets that we want and pass this onto the superclass init
- The decompress method accepts a single value that represents that data from the database, we then break this into two values that our multiwidget can use
@IdeyasMarceloMendes this note was created 8 years ago and I haven't touched Django ever since.