[Fixed]-Django subclassing multiwidget – reconstructing date on post using custom multiwidget

12👍

Answered my own question!

I implemented this method:

def value_from_datadict(self, data, files, name):
    datelist = [widget.value_from_datadict(data, files, name + '_%s' % i) \ 
                                      for i, widget in enumerate(self.widgets)]
    try:
        D = date(day=int(datelist[0]), month=int(datelist[1]), \
             year=int(datelist[2]))
        return str(D)
    except ValueError:
        return ""

value_from_datadict pulls the data of all the sub-widgets from the entire post datadict. What I’ve done is to extract out the various date counterparts, and use the date constructor to validate the date. If it is valid, we print the string out in the correct format, otherwise, we return an empty string which

forminstance.is_valid()

will catch.

I love it when I do this!

Leave a comment