I am getting a key error when trying to print from my dictionary - keyerror

I am getting a Key error "name" when i run the following code. I believe the name in my dictionary to be defined so i am unsure what the source of the error is.
'''
The task is broken down into three sections.
Section 1 - User Input
Section 2 - loop through the grocery list
Section 3 - provide output to the console
'''
Task: Create the empty data structure
grocery_item = {}
grocery_history = []
Variable used to check if the while loop condition is met
stop = False
while not stop :
#Accept input of the name of the grocery item purchased.
name = input("item Name:\n")
#Accept input of the quantity of the grocery item purchased.
quantity = input("quantity purchased:\n")
#Accept input of the cost of the grocery item input (this is a per-item cost).
cost = input("price per item:\n")
#Using the update function to create a dictionary entry which contains the name, number and price entered by the user.
grocery_item = {'item_name':(name), 'quantity':int(quantity), 'cost':float(cost)}
#Add the grocery_item to the grocery_history list using the append function
grocery_history.append(grocery_item)
#Accept input from the user asking if they have finished entering grocery items.
response = input("Would you like to enter another item?\n Type 'c' to continue or 'q' to quit:\n")
if response == 'q':
stop = True
Define variable to hold grand total called 'grand_total'
grand_total = 0
Define a 'for' loop.
for item in grocery_history:
#Calculate the total cost for the grocery_item.
item_total = item['quantity'] * item['cost']
#Add the item_total to the grand_total
grand_total += item_total
#Output the information for the grocery item to match this example:
#2 apple # $1.49 ea $2.98
print("{} {} # ${} ea {}" .format(item['quantity'], item['name'], item['cost'], item_total))
#Set the item_total equal to 0
item_total = 0
Print the grand total
print ("Grand Total: $"(grand_total))
Item name:
Quantity purchased:
Price per item:
Would you like to enter another item?
Type 'c' for continue or 'q' to quit:
Item name:
Quantity purchased:
Price per item:
Would you like to enter another item?
Type 'c' for continue or 'q' to quit:
Item name:
Quantity purchased:
Price per item:
Would you like to enter another item?

The name should be item_name, because this line:
grocery_item = {'item_name':(name), 'quantity':int(quantity), 'cost':float(cost)}
You assigned the input name to item_name.
Therefore, this line:
print("{} {} # ${} ea {}" .format(item['quantity'], item['name'], item['cost'], item_total))
should replace by :
print("{} {} # ${} ea {}" .format(item['quantity'], item['item_name'], item['cost'], item_total))

Related

odoo add validation for double field

I have this odoo py
class CrmProject(models.Model):
_name='crm.project'
customer_id = fields.Many2one('res.partner','Customer')
project_product_id = fields.Many2one('crm.project.product','Project Product')
how to validate and show a warning when the customer_id and project_product_id are inputted together with the same value as the one in the crm.project database? so it must be checked with the database first then show warning if it have the same value with the one in customer_id AND project_product_id input.
For example:
Database table crm.project
customer_id = 1
project_product_id = 2
Will create warning ONLY if input:
customer_id = 1
project_product_id = 2
Beside that no warning will be create
I have tried this but no warning created (update 25-04-2021)
#api.model
def create(self,vals):
vals['name'] = self.env['ir.sequence'].next_by_code('crm.project')
res = super(CrmProject,self).create(vals)
# Add code here
#res= super(CrmProject,self).create(vals)
customer_id = vals.get('crm.project.customer_id')
project_product_id = vals.get('crm.project.project_product_id')
get_customer_id = self.env['crm.project'].search([('customer_id','=',customer_id)])
get_project_product_id = self.env['crm.project'].search([('project_product_id','=',project_product_id)])
if get_customer_id and get_project_product_id:
raise UserError(_('The project has already been set before'))
else:
return res
Any help will be grateful
you can create constraint in your db with :
create unique index name_your_constraint
on crm_project (customer_id, project_product_id);

How to get a variable name that is created in a for loop

Basically I have a for loop that is creating variables based on data in a database, I then have an event listener that is also created based on the for loop and I want to know which text is pressed
Ive tried events in the function, creating a variable for my row.name etc.
for row in db:nrows( "SELECT * FROM Students WHERE Class = '"..class.."'" ) do
print(row.Name)
--track how many students there are
count = count+1
--When displaying the names, put them in line, if they go below 1000 y level, move to the right and go down again
ny = ny + 80
if (ny == 1000) then
nx = nx + 300
ny = 280
end
-- Display students
student[row] = display.newText( sceneGroup, row.Name, nx, ny, native.systemFont, 30 )
--Make a button for every student in the row that goes to studentscene function
student[row]:addEventListener( "tap", studentscene)
end
The function then looks like
local function studentscene()
composer.gotoScene( "student", { time=800, effect="crossFade" } )
end
I want to be able to track which student name was pressed, yet i cannot find a way to do so. I need this so I can track in the database which name it is so I can display their information
you can add it by using params in goto function
`options = {
effect = model,
time = time,
params = params,
}
composer.gotoScene( nextScene , options )`
for example do this params = {student="mohsen"}
and in scene:show function do this :
if event.params then
studen = event.params.name
end

How to print records number in form view in odoo?

I have in my python file this function to count number of records in (Order Lines):
class Class_sale_order(models.Model):
_inherit = 'sale.order'
caseacocher_sale_order = fields.Boolean(string='Print customized')
new_field2 = fields.Integer(compute='function_count_saleorderlines')
#api.depends('order_line')
def function_count_saleorderlines(self):
for rec in self:
rec.new_field2 = len('order_line')
But when i see the form view i find that the value of filed is 10, the problem that i have only 5 records.
len('order_line') returns the size of the string 'order_line' which is 10 that's why you are getting the value 10. Set like following:
rec.new_field2 = len(rec.order_line)

Why invoice line values not passed in tax line in odoo10?

I create a custom field in account.invoice.line .
I added the field in account.invoice.tax
I override the prepare invoice function like this
cost_center_id is Many2one field
def _prepare_tax_line_vals(self, line, tax):
res = super(AccountInvoice, self)._prepare_tax_line_vals(line, tax)
if not res.get('cost_center_id') and line.cost_center_id:
res['cost_center_id'] = line.cost_center_id.id
return res
I print the cost_center values here the value is printed here.
But in account.invoice.tax the values is not there.
How to solve this issue??

Lua (And SQL) Error, attempt to call a boolean value

So I'm getting this error while making an addon for Garrys mod, I've been trying for a while but can't quite figure this error out:
[ERROR] addons/ted_stockmarket/lua/autorun/server/stockmarket_init.lua:6: attempt to call a boolean value
1. loadcompany - addons/ted_stockmarket/lua/autorun/server/stockmarket_init.lua:6
2. unknown - addons/ted_stockmarket/lua/autorun/server/stockmarket_init.lua:20
3. unknown - lua/includes/modules/concommand.lua:54
Files are included in full so line numbers will be exact, doing on pastebin because I can't figure out the formatting on this right now. The code is kind of all over the place, I haven't touched this is a while and half of the stuff in the file is bound to be replaced
include("stockmarketprices.lua")
include("stockmarket_config.lua")
local function loadcompany(cmp)
if cmp != nil and sql.TableExists("stockmarket_sharedata") then sql.Query("INSERT INTO stockmarket_sharedata (Companyshort, Company, Shares, Value) VALUES ('"..cmp[2]..", "..cmp[3]..", "..cmp[4]..", "..cmp[5])"')"
end
end
local function test()
if !sql.TableExists(stockmarket_sharedata) then
print("Stock market performing initial load...")
sql.Query( "CREATE TABLE stockmarket_sharedata ( Companyshort string not null, Company string not null, Shares string not null, Value int not null, Rate decimal not null)" )
print("Stock market done loading, restart your server to apply changes.")
end
if stock1[1] == 1 then loadcompany(stock1)
print(stock1[3].." is done loading!")
end
end
hook.Add("Initialize", "First Load", test)
function sharepricechange(shortname, chance, low, high, direction)
if math.random(1, 100) <= chance then shortname.marketbump = math.random(low, high) end
end
hook.Add( "PlayerSay", "chatcommands", function( ply, text )
local text = string.lower( text )
local amount = tonumber(string.sub(text, 16))
local shares = tonumber(file.Read("stockmarket/lifeinsuranceshrs.txt"))
if string.sub(text, 1, 14) == "/buyshares ins" and amount <= shares then
file.Write("stockmarket/lifeinsuranceshrs.txt", ((tonumber(file.Read("stockmarket/lifeinsuranceshrs.txt"))) - tonumber(string.sub(text, 16))))
print("You have invested! There are now "..file.Read("stockmarket/lifeinsuranceshrs.txt").. " shares left for life insurance")
else end
if text == "/stockmarkethelp" then
ply:PrintMessage(HUD_PRINTCONSOLE, [[ /buyshares "company" "amount" - Purchase a specified amount of shares from a specified company.
/stockmarket - Prints all information about the stock market in console.]])
return("") end
end)
function ResetStockmarket(ply)
if ply:IsUserGroup("superadmin") then
local files, directories = file.Find( "*", "DATA")
print(files[1])
file.Delete("stockmarket")end
if !ply:IsUserGroup("superadmin") then ply:PrintMessage( HUD_PRINTCONSOLE, "You are not the right rank to use this command" )
end
end
concommand.Add( "stockmarket_reset", ResetStockmarket)
concommand.Add( "stockmarket_test", test)
pastebin.com/ERFfnbMc
stock1 = { -- DO NOT CHANGE THE TABLE IDENTIFIER
1, -- First line, determine whether or not you want this company to work
"FLN", -- The shortname of the company, keep 3 letters for consistency
"Flynn's Funerals", -- The name of the company
10000, -- The default amount of shares avaliable
94, -- The starting price of each share
0 -- The rate of the shares change in value, do not touch this.
}
pastebin.com/jbJseUWC