Search code examples
djangodjango-formsdjango-widget

In django forms custom widget return list as value instead of string


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


Solution

  • Well, it's simple: if you have a CharField, then you will get a string as a result, because CharField uses method to_python, that coerces the result to string. You need to create your own Field for this one and return a list.

    OLD

    Could you post the result of:

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

    so we can see, what exactly is returned?

    And could you post the whole test case you are using to deliver the example?