【问题标题】:In django forms custom widget return list as value instead of string在 django 表单中,自定义小部件返回列表作为值而不是字符串
【发布时间】:2011-01-20 11:52:31
【问题描述】:

我正在编写一个自定义小部件,我想返回一个列表作为值。从我能找到的设置返回的值中,您可以创建一个自定义 value_from_datadict 函数。我已经这样做了

def value_from_datadict(self, data, files, name):
    value = data.get(name, None)
    if value:
        # split the sting up so that we have a list of nodes
        tag_list = value.strip(',').split(',')
        retVal = []
        # loop through nodes
        for node in tag_list:
            # node string should be in the form: node_id-uuid
            strVal = str(node).split("-")

            uuid = strVal[-1]
            node_id = strVal[0]

            # create a tuple of node_id and uuid for node
            retVal.append({'id': node_id, 'uuid': uuid})

        if retVal:
            # if retVal is not empty. i.e. we have a list of nodes
            # return this. if it is empty then just return whatever is in data
            return retVal

    return value

我希望这会返回一个列表,但是当我打印出该值时,它会以字符串而不是列表的形式返回。字符串本身包含正确的文本,但正如我所说,它是一个字符串而不是一个列表。返回的示例可能是

[{'id': '1625', 'uuid': None}]

但如果我执行 str[0],它会打印出 [ 而不是 {'id': '1625', 'uuid': None}

如何阻止它将我的列表转换为字符串?

谢谢

【问题讨论】:

  • 对上一个答案添加了编辑。

标签: django django-forms django-widget


【解决方案1】:

嗯,很简单:如果你有一个CharField,那么你会得到一个字符串作为结果,因为CharField 使用了to_python 方法,它将结果强制转换为字符串。您需要为此创建自己的Field 并返回一个列表。

你能发布结果吗:

x = value_from_datadict(..)
print type(x)

所以我们可以看到,究竟返回了什么?

您能否发布您用于交付示例的整个测试用例?

【讨论】:

  • 感谢您的回复。是否有任何示例或您可以指出的地方向我展示这一点,因为我不确定该怎么做?是否没有为列表设置一个字段,例如我可以使用的多项选择字段?
  • 感谢完美。我所做的只是将 value_from_datadict 函数中的代码移动到我的新字段的 clean 函数中,它完全符合我的要求。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-04-03
  • 1970-01-01
  • 1970-01-01
  • 2021-11-30
  • 2022-01-25
  • 2011-05-13
  • 2011-06-12
相关资源
最近更新 更多