django - 来自数据字典的值 : hard to understand

标签 django django-forms

我不明白这个例子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 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.

关于django - 来自数据字典的值 : hard to understand,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35011695/

相关文章:

javascript - Web 框架为程序员提供什么帮助?

python - 将附加信息附加到表单字段

javascript - 如果 session 设置为 true,则打开一个 div

Django:对外部查询的引用只能在子查询中使用

python - 如何在 Jinja 2 中使用 3rd 方应用模板标签?

django - 为简单的调查应用程序生成表单

django-forms - 如何为 django-allauth 登录/注册默认表单提供样式?

Django 自定义表单验证最佳实践?

python - "Cannot update a query once a slice has been taken"。最佳实践?

django - Django postgres IntegerRangeField 的非重叠约束