我不明白这个例子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()
是 Widget
的一种方法抽象类,根据其 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]),
)
一个 MultiWidget
它与采用单个值的 DateField
表单字段一起使用,因此
we have overridden this method to combine the data of all the subwidgets into a
datetime.date
. The method extracts data from thePOST
dictionary and constructs and validates the date. If it is valid, we return the string, otherwise, we return an empty string which will causeform.is_valid
to returnFalse
.
关于django - 来自数据字典的值 : hard to understand,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35011695/