1

我正在编写一个自定义小部件,我想将一个列表作为值返回。根据我能找到的设置返回的值,您可以创建一个自定义 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}

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

谢谢

4

1 回答 1

2

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

老的

您能否发布以下结果:

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

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

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

于 2010-02-24T12:12:58.027 回答