Too Many values to unpack (expected 2) no Django

Asked

Viewed 2,507 times

2

I have this piece of code in Django, the intention is to insert, if there is already the ds_user_id then it updates the user with this ds_user_id instead of creating a new

ds_user_id = int(post_login['ds_user_id'])
csrftoken = post_login['csrftoken']
cookies = json.dumps(str(post_login['cookies']))

defaults = {
  'username': username,
  'password': password,
  'ds_user_id': ds_user_id,
  'csrftoken': csrftoken,
  'cookies': cookies,
  'status': 0
}

try:
  obj = User.objects.get(ds_user_id=ds_user_id)

  for key, value in defaults.keys():
    setattr(obj, key, value)
  obj.save()
except User.DoesNotExist:
  new_values = {
    'username': username,
    'password': password,
    'ds_user_id': ds_user_id,
    'csrftoken': csrftoken,
    'cookies': cookies,
    'status': 0
  }

  new_values.update(defaults)

  obj = User(**new_values)
  obj.save()

The insert worked however, when trying to log in again, I get:

Too Many values to unpack (expected 2)

I’m not getting it very well, but I think it’s this line that’s bugling my code:

for key, value in defaults.keys():
  • 2

    Yes, it is exactly this line that is "bugging". When doing defaults.keys() you get only dictionary keys, not values. If you want both you should use defaults.items().

  • @Andersoncarloswoss, taking advantage of the topic, I would like to improve the question not to receive negative, I’m almost being blocked :( but I have no time

  • 2

    Apergutna is ok. The answer is simple and correct - Anderson’s - that you should have put as an answer. .

1 answer

4


You used the method dict.keys, that returns an eternal object with only dictionary keys and error occurs by deconstructing tuple of a value into two variables.

for key, value in defaults.keys():
    setattr(obj, key, value)

As your intention is to get the key/value pair, use dict.items:

for key, value in defaults.items():
    setattr(obj, key, value)
  • Okay, I was going to blame the documentation, but I went there to see and there this items() asokoaskokaoskokas was my mistake, but through that error clumsy you explained something important to me, thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.