django:ValueError need more than 1 value to unpack - django

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)

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)

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(",")
>>>

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.

Related

Python: Problem with logging.error(traceback.format_exception)

I have following code:
def tearDown(self):
e_type, e_value, tb = sys.exc_info()
if e_type is not None:
logging.error((traceback.format_exception(e_type, e_value, tb)))
when I used Python 2.7 everything works fine, but after upgrade to version 3.6 it doesn't work anymore:
For example I have created some example for testing and I expect error.
def test_create_new_user_without_all_fields1(self):
self.assertEqual('USER_1', 'USER_2')
logging.info('test_create_new_user_without_all_fields1: Passed')
Result in console:
======================================================================
FAIL: test_create_new_user_without_all_fields1 (test_testExample.BaseTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Dev\git\CST\tests\test_testExample.py", line 16, in test_create_new_user_without_all_fields1
self.assertEqual('USER_1', 'USER_2')
AssertionError: 'USER_1' != 'USER_2'
- USER_1
+ USER_2
? +
lets add small print to tearDown:
print (sys.exc_info())
Result:
(None, None, None)
As can we see there is no exceptions anymore, but should be. How to fix this problem ?
e_type, e_value, tb = self._outcome.errors[1][1]
logging.error(''.join(traceback.format_exception(e_type, e_value, tb)))

How to fix this python code that performs login to website

am novice in python.Extracted below code to login to website from an online post, but getting error.
Please help to fix it and an explanation will help me
import requests
with requests.Session() as c:
EMAIL = 'noob.python#gmail.com'
PASSWORD = 'Dabc#123'
URL = 'https://www.linkedin.com/'
c.get(URL)
token = c.cookies['CsrfParam']
# This is the form data that the page sends when logging in
login_data = {loginCsrfParam:token, session_key:EMAIL, session_password:PASSWORD}
# Authenticate
r = c.post(URL, data=login_data)
# Try accessing a page that requires you to be logged in
r = c.get('https://www.linkedin.com/feed/')
print r.content
Am stuck with below Error:
C:\Python27>python website.py
Traceback (most recent call last):
File "website.py", line 8, in <module>
token = c.cookies['CsrfParam']
File "C:\Python27\lib\site-packages\requests\cookies.py", line 329, in __getitem__
return self._find_no_duplicates(name)
File "C:\Python27\lib\site-packages\requests\cookies.py", line 400, in _find_no_duplicates
raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))
KeyError: "name='CsrfParam', domain=None, path=None"
The reason you're getting the error is that you're calling a value from a list which is empty. To call the first item in the list you say list[0]. In this case the list you're calling is empty so the first value doesn't exist hence the error.
I've ran your code and there is no #id value of 'recaptcha-token' which is why the code is returning an empty list. The only place a recaptcha token is needed is for signing up so I would suggest trying to log in without creating the authenticity_token.

Share globals across multiple files

I'm extremely new to python, so I apologize if this is a simple question, I'm creating a program where I need to share a global variable across multiple files. I have a file called settings.py that looks like this:
def init():
global BACKPACK
global SURVIVAL_TOOLS
BACKPACK = {}
SURVIVAL_TOOLS = {}
I import those settings into another file called battle.py and prepare.py:
from settings import init
# battle.py #
def win_battle(animal):
print "You do one final slash and the {} goes limp." \
" You pick it up and start walking back to camp.".format(animal)
init.SURVIVAL_TOOLS['meat'] = 1
if 'camp' in init.SURVIVAL_TOOLS:
return_to_camp()
else:
options = ['create a fire', 'create a camp']
for opt in options:
print "TEST" # TODO: FINISH THIS METHOD
from settings import init
def gather_gear(player):
# prepare.py #
"""
Gather your gear from a set list of items you have available
:type player: String
"""
print formatter()
print "{}! Shouts Jack as he runs towards you." \
" Do you wanna go Hiking this weekend?" \
" You ponder this for a second." \
" What the hell, you think." \
" Can't be any worse then last time." \
" Sure, Jack! You say enthusiastically." \
" Just let me get some things prepared.\n".format(player)
options = { # All the items that are available to you before you leave
'fire starter': 1,
'matches': randint(1, 5), # Uses random integers as the value
'flash light': 1,
'sleeping bag': 1,
'canteen cup': 1,
'dried foods': randint(2, 6),
'shovel': 1,
'knife': 1,
'pair of socks': randint(2, 10),
'granola bars': randint(2, 5),
'machete': 1,
'bottle of whiskey': 1,
'heavy jacket': 1,
'tinder pieces': randint(3, 5)
}
for key in options:
print "You have {} {}".format(options[key], key) # Print out all your items and make it look pretty
count = 3
num_in_pack = 0
print '\n'
while count != 0:
item = raw_input("What would you like to take with you? Choose {} items one at a time: ".format(str(count))).lower()
if item in options and item not in init.BACKPACK: # As long as the item is available you can use it
init.BACKPACK[item] = options[item] # Add the item value to your backpack constant
count -= 1
print "You throw a {} in your backpack".format(item)
num_in_pack += 1
if num_in_pack == 3: # If you have three items, lets begin!
print "Your backpack is now full."
start_adventure(player)
else:
print "Can't bring that item."
return init.BACKPACK
However I get a warning in my IDE that:
Cannot find reference 'SURVIVAL_TOOLS' in 'function' less... (Ctrl+F1 Alt+T)
This inspection detects names that should resolve but don't. Due to dynamic dispatch and duck typing, this is possible in a limited but useful number of cases. Top-level and class-level items are supported better than instance items.
And when this program is run I get:
Traceback (most recent call last):
File "game.py", line 1, in <module>
from prepare import *
File "C:\Users\thomas_j_perkins\bin\python\game\prepare.py", line 1, in <modul
e>
from game import *
File "C:\Users\thomas_j_perkins\bin\python\game\game.py", line 2, in <module>
from choices import *
File "C:\Users\thomas_j_perkins\bin\python\game\choices.py", line 3, in <modul
e>
from prepare import BACKPACK
ImportError: cannot import name BACKPACK
I got the idea of moving all my constants to a single file from this question
So my question is, why am I unable to use the constant variables that I have created in the settings.py file?
EDIT:
I attempted to do init().BACKPACK and am now getting the error:
Traceback (most recent call last):
File "game.py", line 94, in <module>
welcome_screen()
File "game.py", line 85, in welcome_screen
gather_gear(player_name)
File "C:\Users\thomas_j_perkins\bin\python\game\prepare.py", line 45, in gathe
r_gear
if item in options and item not in init().BACKPACK: # As long as the item i
s available you can use it
AttributeError: 'NoneType' object has no attribute 'BACKPACK'
When you do global BACKPACK; BACKPACK = {}, you are creating a module attribute called BACKPACK. To access it, change from settings import init to import settings. This will allow you to use all the module attributes of settings in your code:
settings.SURVIVAL_TOOLS['meat'] = 1
You also need to make sure that settings.init is called once in your program. You can either call it somewhere in your code, or better yet, modify settings.py to look like this:
BACKPACK = {}
SURVIVAL_TOOLS = {}
No function definitions, no globals. This code will get run the first time the module is imported anywhere. Next time is is imported, the dicts will not be modified.

How to solve AttributeError in python active_directory?

Running the below script works for 60% of the entries from the MasterGroupList however suddenly fails with the below error. although my questions seem to be poor ou guys have been able to help me before. Any idea how I can avoid getting this error? or what is trhoughing off the script? The masterGroupList looks like:
Groups Pulled from AD
SET00 POWERUSER
SET00 USERS
SEF00 CREATORS
SEF00 USERS
...another 300 entries...
Error:
Traceback (most recent call last):
File "C:\Users\ks185278\OneDrive - NCR Corporation\Active Directory Access Scr
ipt\test.py", line 44, in <module>
print group.member
File "C:\Python27\lib\site-packages\active_directory.py", line 805, in __getat
tr__
raise AttributeError
AttributeError
Code:
from active_directory import *
import os
file = open("C:\Users\NAME\Active Directory Access Script\MasterGroupList.txt", "r")
fileAsList = file.readlines()
indexOfTitle = fileAsList.index("Groups Pulled from AD\n")
i = indexOfTitle + 1
while i <= len(fileAsList):
fileLocation = 'C:\\AD Access\\%s\\%s.txt' % (fileAsList[i][:5], fileAsList[i][:fileAsList[i].find("\n")])
#Creates the dir if it does not exist already
if not os.path.isdir(os.path.dirname(fileLocation)):
os.makedirs(os.path.dirname(fileLocation))
fileGroup = open(fileLocation, "w+")
#writes group members to the open file
group = find_group(fileAsList[i][:fileAsList[i].find("\n")])
print group.member
for group_member in group.member: #this is line 44
fileGroup.write(group_member.cn + "\n")
fileGroup.close()
i+=1
Disclaimer: I don't know python, but I know Active Directory fairly well.
If it's failing on this:
for group_member in group.member:
It could possibly mean that the group has no members.
Depending on how phython handles this, it could also mean that the group has only one member and group.member is a plain string rather than an array.
What does print group.member show?
The source code of active_directory.py is here: https://github.com/tjguk/active_directory/blob/master/active_directory.py
These are the relevant lines:
if name not in self._delegate_map:
try:
attr = getattr(self.com_object, name)
except AttributeError:
try:
attr = self.com_object.Get(name)
except:
raise AttributeError
So it looks like it just can't find the attribute you're looking up, which in this case looks like the 'member' attribute.

What is the error in following python code

import sys
def Hello(name):
name = name + '!!!'
print 'Hello' , name
def main():
Hello(sys.argv[1])
if __name__ == '__main__':
main()
Here is the error
Traceback (most recent call last):
File "D:\pythonPractice\firstPython.py", line 13, in <module>
main()
File "D:\pythonPractice\firstPython.py", line 9, in main
Hello(sys.argv[1])
IndexError: list index out of range
I have also tried sys.argv[2] but error remains
First things first, I think the code you originally posted (with Hello(sys.argv[0])) is not what you actually have. It doesn't match the error, which states sys.argv[1], so what you probably have is:
def main():
Hello(sys.argv[1])
As to the error then, it's because you haven't provided an argument when running. You need to do so, such that sys.argv[1] exists:
python helloprog Pax
You would find a more robust main as:
def main():
if len(sys.argv) < 2:
Hello("whoever you are")
else:
Hello(sys.argv[1])
which will detect when you haven't provided an argument, and use a suitable default rather than raising an exception.
Have you used
sys.argv[0]
Since this returns a list , you may not have elements >1