在 django 表单中,自定义小部件返回列表作为值而不是字符串
我正在编写一个自定义小部件,我想返回一个列表作为值。根据我可以找到的设置返回的值,您可以创建一个自定义 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}
我怎样才能阻止它将我的列表转换为字符串?
谢谢
I am writting a custom widget which I want to return a list as the value. From what I can find to set the value that is returned you create a custom value_from_datadict function. I have done this
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
I expect this to return a list but when I print out the value it is returned as a string rather than a list. The string itself contains the right text but as i said it is a string and not a list. An example of what is returned could be
[{'id': '1625', 'uuid': None}]
but if I did str[0] it would print out [ instead of {'id': '1625', 'uuid': None}
How can I stop it from converting my list into a string?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
嗯,很简单:如果您有一个
CharField
,那么您将得到一个字符串作为结果,因为CharField
使用方法to_python
,该方法强制结果字符串。您需要为此创建自己的Field
并返回一个列表。OLD
您能否发布结果:
以便我们可以看到,到底返回了什么?
您能否发布您用来提供示例的整个测试用例?
Well, it's simple: if you have a
CharField
, then you will get a string as a result, becauseCharField
uses methodto_python
, that coerces the result to string. You need to create your ownField
for this one and return a list.OLD
Could you post the result of:
so we can see, what exactly is returned?
And could you post the whole test case you are using to deliver the example?