value_from_datadict: 难懂

value_from_datadict: hard to understand

我不明白这个例子here:

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]),
        )
    except ValueError:
        return ''
    else:
        return str(D)

具体来说,我不明白什么时候应该使用widget.value_from_datadict()以及如何使用它。如果您查看源代码本身,它根本没有记录 (django\forms\widgets.py):

def value_from_datadict(self, data, files, name):
    return [widget.value_from_datadict(data, files, name + '_%s' % i) for i, widget in enumerate(self.widgets)]

value_from_datadict() is a method of the Widget abstract class which as per its doc 字符串:

def value_from_datadict(self, data, files, name):
    """
    Given a dictionary of data and this widget's name, returns the value
    of this widget. Returns None if it's not provided.
    """
    return data.get(name)

在您的具体情况下 - 从 docs 我假设

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]),
        )

a MultiWidget 它与采用单个值的 DateField 表单字段一起使用,因此

we have overridden this method to combine the data of all the subwidgets into a datetime.date. The method extracts data from the POST dictionary and constructs and validates the date. If it is valid, we return the string, otherwise, we return an empty string which will cause form.is_valid to return False.