Skip to content

Instantly share code, notes, and snippets.

@bulkan
Created December 6, 2012 03:48
Show Gist options
  • Save bulkan/4221633 to your computer and use it in GitHub Desktop.
Save bulkan/4221633 to your computer and use it in GitHub Desktop.
How To Create a Django MultiWidget

What are MultiWidgets ?

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.

I heard you like Widgets so I put a Widget into your Widget so you can Widget

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
@gutimore
Copy link

gutimore commented Jul 4, 2018

Worked for me, thank you!

@IdeyasMarceloMendes
Copy link

I've difficult to display multiwidget in my temlpate can you help me ?
You could to show one template displaing that

@bulkan
Copy link
Author

bulkan commented Mar 13, 2021

@IdeyasMarceloMendes this note was created 8 years ago and I haven't touched Django ever since.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment