himanka
himanka

Reputation: 23

django:ValueError need more than 1 value to unpack

I'm using ajax and django for dynamically populate a combo box. ajax component works really fine and it parse the data to the view but int the view, when i'm using the spiting function it gives me a exception called "Value Error:need more than 1 value to unpack ". can anyone helps me to figure out the error :) :) code:

def dropdownPopulate(request):



if request.method=='POST' :
    key = request.POST['id']
else:
    key=""



level, tree_id=key.split(",")

next_nodes=Structure.objects.filter(tree_id=key[tree_id]).filter(level=key[level])
context={'name':next_nodes}     
return render_to_response('renderAjax.html',context)    

Upvotes: 2

Views: 5816

Answers (3)

Aamir Rind
Aamir Rind

Reputation: 39659

This is because s.split(',') is returning list of length 1:

level, tree_id = key.split(',')

Make sure it return list of length 2:

parts = key.split(',')
if len(parts) == 2:
    level, tree_id = parts
elif len(parts) == 1:
    level = parts[0]
    tree_id = None
else:
    # do something
    level = tree_id = None
    pass

The apply filter like this:

next_nodes = Structure.objects.all()
if level:
    next_nodes = next_nodes.filter(level=level)
if tree_id:
    next_nodes = next_nodes.filter(tree_id=tree_id)

Upvotes: 1

Rohan
Rohan

Reputation: 53336

You have multiple problems.

level, tree_id=key.split(",")

This will fail, as key may not have ,, so split will not return 2 values.

next_nodes=Structure.objects.filter(tree_id=key[tree_id]).filter(level=key[level])

Here you are accessing key as dict, which is incorrect as it is string.

Upvotes: 0

stalk
stalk

Reputation: 12054

Probably error occurs at this line:

level, tree_id=key.split(",")

It is needed to handle the situation, when key will not have ",". Or maybe it will have more than one ",".

Look at your code:

if request.method=='POST' :
    key = request.POST['id']
else:
    key=""

It is possible, that key will be a blank string.

Here are examples, when error can occur:

1.

>>> key = ""
>>> level, tree_id=key.split(",")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: need more than 1 value to unpack

2.

>>> key = "a,b,c"
>>> level, tree_id=key.split(",")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack

Only this will be fine (when it is only one ","):

>>> key = "a,b"
>>> level, tree_id=key.split(",")
>>> 

Upvotes: 0

Related Questions