Python Mysql request thru query storage for B3 (BigBrotherBot) - python-2.7
I try to retrive MysqlDatabase Data from a given Database (maprating).
When i call the command !maprating i get the following Error:
230205 14:19:09 DEBUG 'AdminPlugin: handle command !maprating'
230205 14:19:09 VERBOSE "RCON sending (127.0.0.1:27960) 'tell 0 ^3: ^8[pm]^7 ^7There was an error processing your command'"
230205 14:19:09 ERROR "Handler AdminPlugin could not handle event Say: AttributeError: 'Cursor' object has no attribute 'fetchone'
This is the code i use for the maprating query. It should get me the average rating of the maps.
Important! the Python syntax needs to be for Python 2.7.* as the B3 Bot can only handle to this version of python.
def cmd_maprating(self, data, client, cmd=None):
map_name = self.console.game.mapName
query = "SELECT map_name, SUM(rating) AS total_rating FROM mapratings WHERE map_name = %s GROUP BY map_name"
cursor = self.console.storage.query(query, (map_name,))
if cursor.rowcount == 0:
client.message("No ratings for map %s" % map_name)
else:
result = cursor.fetchone()
client.message("Map %s has a total rating of %d" % (result['map_name'], result['total_rating']))
**Here is the complete code.
**
import os
import sys
import b3
import b3.events
import b3.plugin
class MapratingPlugin(b3.plugin.Plugin):
def onLoadConfig(self):
self.rated_players = {}
self.map_ratings = {}
def onStartup(self):
self.registerEvent(b3.events.EVT_CLIENT_SAY)
self._adminPlugin = self.console.getPlugin('admin')
if self._adminPlugin:
self._adminPlugin.registerCommand(self, 'rategood', 0, self.cmd_rategood)
self._adminPlugin.registerCommand(self, 'ratebad', 0, self.cmd_ratebad)
self._adminPlugin.registerCommand(self, 'maprating', 0, self.cmd_maprating)
def is_rated(self, client, map_name):
cursor = self.console.storage.query("""
SELECT rating FROM mapratings WHERE guid = %s AND map_name = %s
""", (client.guid, map_name))
if cursor.rowcount:
return (True, cursor.getRow()['rating'])
else:
return (False, 0)
def add_rating(self, client, map_name, rating):
self.console.storage.query("""
INSERT INTO mapratings (guid, player_name, map_name, rating)
VALUES (%s, %s, %s, %s)
""", (client.guid, client.name, map_name, rating))
def update_rating(self, client, map_name, rating):
self.console.storage.query("""
UPDATE mapratings SET rating = %s WHERE guid = %s AND map_name = %s
""", (rating, client.guid, map_name))
def cmd_rategood(self, data, client, cmd=None):
map_name = self.console.game.mapName
(is_rated, existing_rating) = self.is_rated(client, map_name)
rating = 1
if is_rated:
if existing_rating == rating:
client.message('You have already rated this map as good')
else:
self.update_rating(client, map_name, rating)
client.message('Map %s rated as good by you' % map_name)
else:
self.add_rating(client, map_name, rating)
client.message('Map %s rated as good by you' % map_name)
def cmd_ratebad(self, data, client, cmd=None):
map_name = self.console.game.mapName
(is_rated, existing_rating) = self.is_rated(client, map_name)
rating = -1
if is_rated:
if existing_rating == rating:
client.message('You have already rated this map as bad')
else:
self.update_rating(client, map_name, rating)
client.message('Map %s rated as bad by you' % map_name)
else:
self.add_rating(client, map_name, rating)
client.message('Map %s rated as bad by you' % map_name)
def cmd_maprating(self, data, client, cmd=None):
map_name = self.console.game.mapName
query = "SELECT map_name, SUM(rating) AS total_rating FROM mapratings WHERE map_name = %s GROUP BY map_name"
cursor = self.console.storage.query(query, (map_name,))
if cursor.rowcount == 0:
client.message("No ratings for map %s" % map_name)
else:
result = cursor.fetchone()
client.message("Map %s has a total rating of %d" % (result['map_name'], result['total_rating']))
Thank you.
I got the problem solved by using the curser.getRow instead of fetchone() command that is supported by the B3 Bot given librarys.
def cmd_maprating(self, data, client, cmd=None):
map_name = self.console.game.mapName
query = "SELECT map_name, SUM(rating) AS total_rating FROM mapratings WHERE map_name = %s GROUP BY map_name"
cursor = self.console.storage.query(query, (map_name,))
if cursor.rowcount == 0:
client.message("No ratings for map %s" % map_name)
else:
result = cursor.getRow()
rating = result['total_rating']
if rating >= 0:
client.message("Map %s has a total rating of ^2%d" % (result['map_name'], rating))
else:
client.message("Map %s has a total rating of ^1%d" % (result['map_name'], rating))
Related
elif condition in django view
I'm having view function which filters object according to the data I give and if that filtered object does not exist in the database it adds the object to DB(i didn't write add function yet). Shows error if it exists already. I'm getting data from a template using ajax post request. #view.py #csrf_exempt def setUserInDB(request): if request.method=="POST": if request.POST.get('pname','u_id'): pname = request.POST.get('pname') u_id = request.POST.get('u_id') user = userprofile.objects.get(pk=u_id) pid = Project.objects.get(title=pname) else: u_id = None pname = None if request.POST.get('db_id','chkbox'): db_id = request.POST.get('db_id') db = Db_profile.objects.get(pk=db_id) chkbox = request.POST.get('chkbox') print chkbox else: db_id = None chkbox = None if Projectwiseusersetup.objects.filter(userid=user,project_id=pid, db_profileid= db,setasdefaultproject=chkbox): print "already exist" elif (((Projectwiseusersetup.objects.filter(userid = user,project_id = pid,db_profileid=db,setasdefaultproject=False)).exists()) and (chkbox==True)): print "FtoT" elif Projectwiseusersetup.objects.filter(userid = user,project_id = pid,db_profileid=db,setasdefaultproject=True) and chkbox==False: print "TtoF" else: print "aaaa" user,pid,db,chkbox }---- i'm getting these data from ajax post request, userid, project_id, db_profileid, setasdefaultproject(boolean) }----- model fields when I try to check my elif condition, i'm getting output in console "aaaa"(else part). what is wrong with elif?
Here the ex: x = 4 if x == 1: print ("1") elif (x == 2): print("2") elif (x == 3): print("3") else: print("4")
Invoice number and taxes amounts creating invoices from custom Odoo module
I'm migrating invoices from OpenERP 7 database to Odoo8. I'm retrieving OERP7 data with psycopg2 and then using envs and model.create() to insert invoices into Odoo8 database. In general, the code works fine, but Odoo8 is not generating the invoice number (associated to account_move table) and amount_tax. My codes are the following: Import Account Invoice class ImportAccountInvoice(Command): """Import account invoices from source DB""" def process_account_invoice(self, model, data): if not data: return # Model structure model.create({ 'account_id': data['account_id'], 'amount_tax': data['amount_tax'], 'amount_total': data['amount_total'], 'amount_untaxed': data['amount_untaxed'], 'check_total': data['check_total'], 'company_id': data['company_id'], 'currency_id': data['currency_id'], 'date_due': data['date_due'], 'date_invoice': data['date_invoice'], 'fiscal_position': data['fiscal_position'], 'internal_number': data['internal_number'], 'move_name': data['move_name'], 'name': data['name'], 'origin': data['origin'], 'partner_id': data['partner_id'], 'period_id': data['period_id'], 'reconciled': data['reconciled'], 'reference': data['reference'], 'residual': data['residual'], 'state': data['state'], 'type': data['type'], 'ship_addr_city': data['ship_addr_city'], 'ship_addr_name': data['ship_addr_name'], 'client_notes': data['client_notes'], 'ship_addr_state': data['ship_addr_state'], 'ship_addr_street': data['ship_addr_street'], 'ship_addr_phone': data['ship_addr_phone'], 'ship_addr_zip': data['ship_addr_zip'], 'drupal_order_name': data['drupal_order_name'], 'payment_method': data['payment_method'], 'drupal_total': data['drupal_total'] }) def run(self, cmdargs): print "Importing account invoices" execute_old_database_query(""" SELECT i.id, i.account_id, i.amount_tax, i.amount_total, i.amount_untaxed, i.check_total, i.company_id, i.currency_id, i.date_due, i.date_invoice, i.fiscal_position, i.internal_number, i.journal_id, i.move_name, i.name, i.origin, i.partner_id, i.period_id, i.reconciled, i.reference, i.residual, i.sent, i.state, i.type, i.x_dir_city, i.x_dir_name, i.x_dir_observations, i.x_dir_state, i.x_dir_street, i.x_dir_telephone, i.x_dir_zip, i.x_drupal_order, i.x_pago, i.x_total, rp.id, rp.email, rp.name, rp.type, rp.vat, rp.street, rc.id, rc.name, aa.id, aa.code, aa.name, ap.id, ap.code, ap.name, ap.date_start, ap.date_stop, aj.type, aj.code, fp.name FROM account_invoice i LEFT JOIN res_partner rp ON rp.id = i.partner_id LEFT JOIN res_currency rc ON rc.id = i.currency_id LEFT JOIN account_account aa ON aa.id = i.account_id LEFT JOIN account_period ap ON ap.id = i.partner_id LEFT JOIN account_journal aj ON aj.id = i.journal_id LEFT JOIN account_fiscal_position fp ON fp.id = i.fiscal_position ORDER BY i.id; """) openerp.tools.config.parse_config(cmdargs) dbname = openerp.tools.config['db_name'] r = modules.registry.RegistryManager.get(dbname) cr = r.cursor() with api.Environment.manage(): env = api.Environment(cr, 1, {}) # Define target model account_invoice = env['account.invoice'] id_ptr = None c_data = {} while True: r = src_cr.fetchone() if not r: self.process_account_invoice(account_invoice, c_data) break print r account = env['account.account'].search([('code','=',r[43]),('name','=',r[44]),]) currency = env['res.currency'].search([('name','=',r[41]),]) period = match_account_period(env,code=r[46],name=r[47],date_start=r[48],date_stop=r[49]) journal = match_account_journal(env,type=r[50],code=r[51]) fiscal_position = match_account_fiscal_position(env,name=r[52]) company_id = 1 if r[38] is not None and r[39] is not None: partner = env['res.partner'].search([('email','=',r[35]),('name','=',r[36]),('type','=',r[37]),('vat','=',r[38]),('street','=',r[39])]) elif r[38] is not None: partner = env['res.partner'].search([('email','=',r[35]),('name','=',r[36]),('type','=',r[37]),('vat','=',r[38])]) elif r[39] is not None: partner = env['res.partner'].search([('email','=',r[35]),('name','=',r[36]),('type','=',r[37]),('street','=',r[39])]) else: partner = env['res.partner'].search([('email','=',r[35]),('name','=',r[36]),('type','=',r[37])]) # Take one when partners are duplicated partner_id = partner.id if len(list(partner)) <= 1 else partner[0].id fiscal_position_id = fiscal_position.id if fiscal_position else None if id_ptr != r[0]: self.process_account_invoice(account_invoice, c_data) id_ptr = r[0] c_data = { 'id': r[0], 'account_id': account.id, 'amount_tax': r[2], 'amount_total': r[3], 'amount_untaxed': r[4], 'check_total': r[5], 'company_id': company_id, 'currency_id': currency.id, 'date_due': r[8], 'date_invoice': r[9], 'fiscal_position': fiscal_position_id, 'internal_number': r[11], 'journal_id': journal.id, 'move_name': r[13], 'name': r[14], 'origin': r[15], 'partner_id': partner_id, 'partner_invoice_id': partner_id, 'partner_shipping_id': partner_id, 'period_id': period.id, 'reconciled': r[18], 'reference': r[19], 'residual': r[20], 'sent': r[21], 'state': r[22], 'type': r[23], 'ship_addr_city': r[24], 'ship_addr_name': r[25], 'client_notes': r[26], 'ship_addr_state': r[27], 'ship_addr_country': '', 'ship_addr_street': r[28], 'ship_addr_phone': r[29], 'ship_addr_zip': r[30], 'drupal_order_name': r[31], 'payment_method': r[32], 'drupal_total': r[33] } cr.commit() cr.close() Import Account Invoice Lines class ImportAccountInvoiceLine(Command): """Import account invoice lines from source DB""" def process_account_invoice_line(self, model, data): if not data: return # Model structure m = { 'account_id': data['account_id'], 'create_date': data['create_date'], 'company_id': data['company_id'], 'discount': data['discount'], 'invoice_id': data['invoice_id'], 'name': data['name'], 'partner_id': data['partner_id'], 'product_id': data['product_id'], 'quantity': data['quantity'], 'price_unit': data['price_unit'], 'price_subtotal': data['price_subtotal'], 'supplier_name': data['supplier_name'], 'supplier_ref': data['supplier_ref'], 'item_lot_number': data['item_lot_number'], 'item_expiration': data['item_expiration'], 'item_delivery_note': data['item_delivery_note'], } if not data['invoice_line_tax_id'] is None: m['invoice_line_tax_id'] = [(4,data['invoice_line_tax_id'])] # http://stackoverflow.com/questions/31853402/filling-many2many-field-odoo-8 print model.create(m) def recalculate_tax_amount(self,cr): with api.Environment.manage(): env = api.Environment(cr, 1, {}) invoices = env['account.invoice'].search([]) account_invoice_tax = env['account.invoice.tax'] print "Recalculating invoice taxes" for invoice in invoices: print invoice print invoice.action_move_create() # print invoice.button_reset_taxes() if invoice.id <= 32600: break def run(self, cmdargs): print "Importing account invoice lines" execute_old_database_query(""" SELECT il.id, il.account_id, il.create_date, il.company_id, il.discount, il.invoice_id, il.name, il.partner_id, il.price_unit, il.price_subtotal, il.product_id, il.quantity, il.x_prov, il.x_ref_prov, il.x_lote, il.x_caducidad, il.x_albaran, i.internal_number, i.name, i.origin, i.reference, i.type, i.x_drupal_order, i.date_invoice, rp.email, rp.name, rp.type, rp.vat, rp.street, pp.default_code, pp.name_template, pp.x_subcategoria, pp.x_marca, at.type_tax_use, at.name FROM account_invoice_line il LEFT JOIN account_invoice i ON i.id = il.invoice_id LEFT JOIN res_partner rp ON rp.id = il.partner_id LEFT JOIN product_product pp ON pp.id = il.product_id LEFT JOIN account_invoice_line_tax ailt ON ailt.invoice_line_id = il.id LEFT JOIN account_tax at ON at.id = ailt.tax_id WHERE il.id > 28700 ORDER BY il.id DESC; """) openerp.tools.config.parse_config(cmdargs) dbname = openerp.tools.config['db_name'] r = modules.registry.RegistryManager.get(dbname) cr = r.cursor() with api.Environment.manage(): env = api.Environment(cr, 1, {}) # Define target model account_invoice_line = env['account.invoice.line'] id_ptr = None c_data = {} company_id = 1 while True: r = src_cr.fetchone() if not r: self.process_account_invoice_line(account_invoice_line, c_data) break print r print r[17],r[18],r[19],r[20],r[21] if not (r[17] is None and r[18] is None and r[19] is None and r[20] is None): account_invoice = env['account.invoice'].search([('internal_number','=',r[17]),('name','=',r[18]),('origin','=',r[19]),('reference','=',r[20]),('type','=',r[21]),('drupal_order_name','=',r[22]),('date_invoice','=',r[23])]) print "normal" else: print "parner" if r[27] is not None and r[28] is not None: partner = env['res.partner'].search([('email','=',r[24]),('name','=',r[25]),('type','=',r[26]),('vat','=',r[27]),('street','=',r[28])]) elif r[27] is not None: partner = env['res.partner'].search([('email','=',r[24]),('name','=',r[25]),('type','=',r[26]),('vat','=',r[27])]) elif r[28] is not None: partner = env['res.partner'].search([('email','=',r[24]),('name','=',r[25]),('type','=',r[26]),('street','=',r[28])]) else: partner = env['res.partner'].search([('email','=',r[24]),('name','=',r[25]),('type','=',r[26])]) # Take one when partners are duplicated partner_id = partner.id if len(list(partner)) <= 1 else partner[0].id account_invoice = env['account.invoice'].search([('internal_number','=',r[17]),('name','=',r[18]),('origin','=',r[19]),('reference','=',r[20]),('type','=',r[21]),('drupal_order_name','=',r[22]),('date_invoice','=',r[23]),('partner_id','=',partner_id)]) if not account_invoice: # If there is not an account_invoice for this partner, continue with the next row print "^ NO INVOICE FOR THIS LINE ^" continue product = env['product.product'].search([('default_code','=',r[29]),('name_template','=',r[30]),('subcategory_txt','=',r[31]),('brand','=',r[32])]) # Take one when invoices are duplicated invoice = account_invoice if len(list(account_invoice)) <= 1 else account_invoice[0] # Take one when products are duplicated product_id = product.id if len(list(product)) <= 1 else product[0].id print r[33],r[34] if r[33] is None and r[34] is None: tax_id = None else: tax = match_account_tax(env, r[33], r[34]) tax_id = tax.id if id_ptr != r[0]: self.process_account_invoice_line(account_invoice_line, c_data) id_ptr = r[0] c_data = { 'id': r[0], 'account_id': invoice.account_id.id, 'create_date': r[2], 'company_id': r[3], 'discount': r[4], 'invoice_id': invoice.id, 'name': r[6], 'partner_id': invoice.partner_id.id, 'price_unit': r[8], 'price_subtotal': r[9], 'product_id': product_id, 'quantity': r[11], 'supplier_name': r[12], 'supplier_ref': r[13], 'item_lot_number': r[14], 'item_expiration': r[15], 'item_delivery_note': r[16], 'invoice_line_tax_id': tax_id } cr.commit() self.recalculate_tax_amount(cr) cr.close() I have associated Journals, Periods... but I can't get Odoo creates the account.move and compute all taxes. What should I do? IMPORTANT: I need to assign the same number each invoice already have in old database.
The solution was to create a function to update invoice taxes and move, at the end of invoice lines insertion and before commit. The function: def refresh_invoices_and_recompute_taxes(self, model, invoice_ids): for i in invoice_ids: print "Updating invoice", i invoice = model.browse(i) print "- Computing taxes" invoice.button_compute(set_total=True) invoice.action_date_assign() print "- Creating account move" invoice.action_move_create() print "- Assigning number" invoice.action_number() My class: class ImportAccountInvoiceLine(Command): """Import account invoice lines from source DB""" def process_account_invoice_line(self, model, data): if not data: return m = { 'account_id': data['account_id'], 'create_date': data['create_date'], 'company_id': data['company_id'], 'discount': data['discount'], 'invoice_id': data['invoice_id'], 'name': data['name'], 'partner_id': data['partner_id'], 'product_id': data['product_id'], 'quantity': data['quantity'], 'price_unit': data['price_unit'], 'price_subtotal': data['price_subtotal'], 'supplier_name': data['supplier_name'], 'supplier_ref': data['supplier_ref'], 'item_lot_number': data['item_lot_number'], 'item_expiration': data['item_expiration'], 'item_delivery_note': data['item_delivery_note'], } if not data['invoice_line_tax_id'] is None: m['invoice_line_tax_id'] = [(4,data['invoice_line_tax_id'])] # http://stackoverflow.com/questions/31853402/filling-many2many-field-odoo-8 # Model structure model.create(m) def refresh_invoices_and_recompute_taxes(self, model,invoice_ids): for i in invoice_ids: print "Updating invoice", i invoice = model.browse(i) print "- Computing taxes" invoice.button_compute(set_total=True) invoice.action_date_assign() print "- Creating account move" invoice.action_move_create() print "- Assigning number" invoice.action_number() def run(self, cmdargs): print "Importing account invoice lines" execute_old_database_query(""" SELECT il.id, il.account_id, il.create_date, il.company_id, il.discount, il.invoice_id, il.name, il.partner_id, il.price_unit, il.price_subtotal, il.product_id, il.quantity, il.x_prov, il.x_ref_prov, il.x_lote, il.x_caducidad, il.x_albaran, i.internal_number, i.name, i.origin, i.reference, i.type, i.x_drupal_order, i.date_invoice, rp.email, rp.name, rp.type, rp.vat, rp.street, pp.default_code, pp.name_template, pp.x_subcategoria, pp.x_marca, at.type_tax_use, at.name FROM account_invoice_line il LEFT JOIN account_invoice i ON i.id = il.invoice_id LEFT JOIN res_partner rp ON rp.id = il.partner_id LEFT JOIN product_product pp ON pp.id = il.product_id LEFT JOIN account_invoice_line_tax ailt ON ailt.invoice_line_id = il.id LEFT JOIN account_tax at ON at.id = ailt.tax_id ORDER BY il.invoice_id ASC, il.id ASC LIMIT 10000; """) openerp.tools.config.parse_config(cmdargs) dbname = openerp.tools.config['db_name'] r = modules.registry.RegistryManager.get(dbname) cr = r.cursor() invoice_ids = [] inv_id = 0 with api.Environment.manage(): env = api.Environment(cr, 1, {}) # Define target model account_invoice_line = env['account.invoice.line'] id_ptr = None c_data = {} company_id = 1 while True: r = src_cr.fetchone() if not r: self.process_account_invoice_line(account_invoice_line, c_data) break if not (r[17] is None and r[18] is None and r[19] is None and r[20] is None): account_invoice = env['account.invoice'].search([('internal_number','=',r[17]),('name','=',r[18]),('origin','=',r[19]),('reference','=',r[20]),('type','=',r[21]),('drupal_order_name','=',r[22]),('date_invoice','=',r[23])]) else: if r[27] is not None and r[28] is not None: partner = env['res.partner'].search([('email','=',r[24]),('name','=',r[25]),('type','=',r[26]),('vat','=',r[27]),('street','=',r[28])]) elif r[27] is not None: partner = env['res.partner'].search([('email','=',r[24]),('name','=',r[25]),('type','=',r[26]),('vat','=',r[27])]) elif r[28] is not None: partner = env['res.partner'].search([('email','=',r[24]),('name','=',r[25]),('type','=',r[26]),('street','=',r[28])]) else: partner = env['res.partner'].search([('email','=',r[24]),('name','=',r[25]),('type','=',r[26])]) # Take one when partners are duplicated partner_id = partner.id if len(list(partner)) <= 1 else partner[0].id account_invoice = env['account.invoice'].search([('internal_number','=',r[17]),('name','=',r[18]),('origin','=',r[19]),('reference','=',r[20]),('type','=',r[21]),('drupal_order_name','=',r[22]),('date_invoice','=',r[23]),('partner_id','=',partner_id)]) if not account_invoice: # If there is not an account_invoice for this partner, continue with the next row print "^ NO INVOICE FOR THIS LINE ^" continue product = env['product.product'].search([('default_code','=',r[29]),('name_template','=',r[30]),('subcategory_txt','=',r[31]),('brand','=',r[32])]) # Take one when invoices are duplicated invoice = account_invoice if len(list(account_invoice)) <= 1 else account_invoice[0] # Take one when products are duplicated product_id = product.id if len(list(product)) <= 1 else product[0].id if not invoice: continue else: if inv_id != invoice.id: inv_id = invoice.id invoice_ids.append(inv_id) tax = match_account_tax(env, r[33], r[34]) tax_id = tax.id if tax is not None and tax else None if id_ptr != r[0]: id_ptr = r[0] c_data = { 'id': r[0], 'account_id': invoice.account_id.id, 'create_date': r[2], 'company_id': r[3], 'discount': r[4], 'invoice_id': invoice.id, 'name': r[6], 'partner_id': invoice.partner_id.id, 'price_unit': r[8], 'price_subtotal': r[9], 'product_id': product_id, 'quantity': r[11], 'supplier_name': r[12], 'supplier_ref': r[13], 'item_lot_number': r[14], 'item_expiration': r[15], 'item_delivery_note': r[16], 'invoice_line_tax_id': tax_id } self.process_account_invoice_line(account_invoice_line, c_data) self.refresh_invoices_and_recompute_taxes(env['account.invoice'], invoice_ids) cr.commit() cr.close()
Odoo - How to get report data based on company_id
I'm trying to get payroll data for each company's employees in a report based on company_id. Here's my code: in my wizard: class hr_wps_report(osv.osv_memory): _name = 'hr.wps.report' _description = 'WPS Report' _columns = { 'date_from':fields.date("Start Date"), 'date_to':fields.date("End Date"), 'company_id': fields.many2one('res.company', 'Company', select=True, required=False), } _defaults = { 'date_from': lambda *a: time.strftime('%Y-%m-01'), 'date_to': lambda *a: str(datetime.now() + relativedelta.relativedelta(months=+1, day=1, days=-1))[:10], 'company_id': lambda self, cr, uid, context: self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id, } def print_report(self, cr, uid, ids, data, context=None): if context is None: context = {} data['form'] = self.read(cr, uid, ids, ['date_from', 'date_to', 'company_id'], context=context)[0] return self.pool['report'].get_action(cr, uid, [], 'hr_wps.report_wpsreport', data=data, context=context) in my report: class wpsreport(report_sxw.rml_parse): def __init__(self, cr, uid, name, context): super(wpsreport, self).__init__(cr, uid, name, context=context) self.localcontext.update({ 'time': time, 'get_lines': self._get_lines, }) def set_context(self, objects, data, ids, report_type=None): self.date_start = data['form'].get('date_from', time.strftime('%Y-%m-%d')) self.date_end = data['form'].get('date_to', time.strftime('%Y-%m-%d')) self.company_id = data['form'].get('company_id') return super(wpsreport, self).set_context(objects, data, ids, report_type=report_type) def _get_lines(self, form): res = [] self.cr.execute("""SELECT hr_employee.name_related, (SELECT hr_payslip_line.total FROM hr_payslip_line, hr_payslip WHERE hr_employee.id = hr_payslip.employee_id AND hr_payslip_line.slip_id = hr_payslip.id AND hr_payslip_line.code = 'BASIC' AND hr_payslip.date_from BETWEEN %s AND %s) as basic, (SELECT hr_payslip_line.total FROM hr_payslip_line, hr_payslip WHERE hr_employee.id = hr_payslip.employee_id AND hr_payslip_line.slip_id = hr_payslip.id AND hr_payslip_line.code = 'ALLOWANCES' AND hr_payslip.date_from BETWEEN %s AND %s) as total_allowance, (SELECT hr_payslip_line.total FROM hr_payslip_line, hr_payslip WHERE hr_employee.id = hr_payslip.employee_id AND hr_payslip_line.slip_id = hr_payslip.id AND hr_payslip_line.code = 'DEDUCTIONS' AND hr_payslip.date_from BETWEEN %s AND %s) as total_deduction, (SELECT hr_payslip_line.total FROM hr_payslip_line, hr_payslip WHERE hr_employee.id = hr_payslip.employee_id AND hr_payslip_line.slip_id = hr_payslip.id AND hr_payslip_line.code = 'NET' AND hr_payslip.date_from BETWEEN %s AND %s) as total FROM hr_employee, hr_payslip, res_company WHERE hr_payslip.employee_id = hr_employee.id AND hr_payslip.company_id = res_company.id AND hr_payslip.date_from BETWEEN %s AND %s AND hr_payslip.company_id = %s""", (self.date_start, self.date_end, self.date_start, self.date_end, self.date_start, self.date_end, self.date_start, self.date_end, self.date_start, self.date_end, self.company_id)) employees = self.cr.dictfetchall() for emp in employees: value = {} value['name_related'] = emp['name_related'] value['basic'] = emp['basic'] value['total_allowance'] = emp['total_allowance'] value['total_deduction'] = emp['total_deduction'] value['total'] = emp['total'] value['No_working_days'] = 30 value['extra_hours'] = 0 res.append(value) return res But I'm getting Error of: QWebException: "invalid input syntax for integer: "Yourcompany" AND hr_payslip.company_id = ARRAY[9, 'Yourcompany'] How to fix it?
Try with: hr_payslip.company_id.id
well I found an answer for my problem and it fixed it instead of self.company_id in the sql query replace it with self.company_id[0]
django save not working as update in views.py with model having an overridden save
I've looked at all the related answers but none fixed my issue. I'm trying to save an object that's already created with no luck. I could see the view getting executed and the values I updated for the object but changes are not reflecting in the database. Here is the code snippet of the view and the model. views.py class Workspace(_LoggedInMixin, View): def get(self, request): user = self.request.user components = ComponentModel.objects.filter(Q(user=user) | Q(user=None)).order_by('time') component_status = request.session.get('component', None) request.session['component'] = None params = dict(components=components, status=component_status) return render(request, 'workspace.html', params) def post(self, request): data = request.POST formtype = data['form-type'] error = None user = self.request.user if formtype == 'component': if data['action'] == 'create': try: if not os.path.exists('D:/' + self.request.user.username): os.makedirs('D:/' + self.request.user.username) cparent = ComponentModel.objects.get(pk=data['cparent']) component = ComponentModel(user=user, name=data['cname'], time=dt.now(), stats=data['cstats'], output=data['coutput'], parent=cparent) component.save() file = open('D:/' + self.request.user.username + '/' + str(component.id) + '.py', 'w+') usercode = data['usercode'] usercode = "\n".join(usercode.split("\r\n")) file.write(usercode) component.codefile = 'D:/' + self.request.user.username + '/' + str(component.id) + '.py' component.save() request.session['component'] = {'name': data['cname'], 'message': 'Component created successfully!'} except Exception as e: component.delete() error = e.message elif data['action'] == 'delete': try: c = ComponentModel.objects.get(pk=data['compid']) cname = c.name c.delete() os.remove('D:/' + self.request.user.username + '/' + data['compid'] + '.py') request.session['component'] = {'name': cname, 'message': 'Component deleted successfully!'} except Exception as e: error = e.message elif data['action'] == 'save': try: if not os.path.exists('D:/' + self.request.user.username): os.makedirs('D:/' + self.request.user.username) cparent = ComponentModel.objects.get(pk=data['cparent']) component = ComponentModel.objects.get(pk=data['compid']) component.user = user component.name = data['cname'] component.time = dt.now() component.stats = data['cstats'] component.output = data['coutput'] component.parent = cparent component.save() print component file = open('D:/' + self.request.user.username + '/' + str(component.id) + '.py', 'w+') usercode = data['usercode'] usercode = "\n".join(usercode.split("\r\n")) file.write(usercode) request.session['component'] = {'name': data['cname'], 'message': 'Component saved successfully!'} except Exception as e: error = e.message if error is not None: components = ComponentModel.objects.filter(Q(user=user) | Q(user=None)).order_by('time') params = dict(error=error, components=components) return render(request, 'workspace.html', params) return redirect('/workspace') models.py class ComponentModel(models.Model): class Meta: # overriding the default table name with the following name db_table = 'components' verbose_name = 'components' get_latest_by = 'time' user = models.ForeignKey('auth.User', on_delete=models.CASCADE, null=True) name = models.CharField(max_length=255) time = models.DateTimeField(db_column='created_on') codefile = models.CharField(max_length=100, db_column='code_file_name', null=True) stats = models.TextField(db_column='statistical_fields', null=True) output = models.TextField(db_column='output_fields') parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True) def save(self, *args, **kwargs): try: super(ComponentModel, self).save(self, *args, **kwargs) except Exception as e: return "Something went wrong while saving the component. Details - %s" % e.message def __str__(self): return "{id: %s, name: %s, user: %s, time: %s, parent: %s}" % ( self.id, self.name, self.user, self.time, self.parent) The second save call in data['action'] == 'create' and the save call in data['action'] == 'save' are not updating the database. I appreciate any help. Thank you.
Your super call is incorrect. Update so that self is not called as a method argument - as you have it written it will always fail. In addition, you are not raising the exception when a save is not completed, so you have no idea if there was an error unless viewing the std output. You probably want this to actually raise an error. Update as such - def save(self, *args, **kwargs): try: super(ComponentModel, self).save(*args, **kwargs) except Exception as e: raise Exception("Something went wrong while saving the component. Details - %s" % (e.message,))
Render data on two templates from one function Django
Hi i need to render the data on two templates from one function my code is def stylepoints(request): a=Product.objects.all()[:3] cursor = connection.cursor() try: cursor.execute("SELECT facebook_id,name FROM django_facebook_facebookuser WHERE user_id = %s ORDER BY RAND() LIMIT 1",[request.user.id]) except Exception as e: return HttpResponse("error in fetching Friends") rows_affected=cursor.rowcount if rows_affected > 0: row1 = cursor.fetchall() row12 = row1[0] else: row12 = '' value = request.user.id cursor12 = connection.cursor() cursor12.execute("SELECT Distinct email FROM myaccount_invitation WHERE reference_id = %s AND status = 1 AND invitation_type = 2",[value]) friend = cursor12.fetchall() if friend: friends = friend[0] return render_to_response('swf.html',{'a':a,'userf':row12,'friendshow':friend} , context_instance=RequestContext(request)) like in this i have send a data to one template name as swf.html but i need to send the data also to another template such as swf2.html please tell me can i render a data to two templates
def view1(request): template_name='swf1.html' return stylepoints(request, template_name) def view2(request): template_name='swf2.html' return stylepoints(request, template_name) def stylepoints(request, template_name): a=Product.objects.all()[:3] cursor = connection.cursor() try: cursor.execute("SELECT facebook_id,name FROM django_facebook_facebookuser WHERE user_id = %s ORDER BY RAND() LIMIT 1",[request.user.id]) except Exception as e: return HttpResponse("error in fetching Friends") rows_affected=cursor.rowcount if rows_affected > 0: row1 = cursor.fetchall() row12 = row1[0] else: row12 = '' value = request.user.id cursor12 = connection.cursor() cursor12.execute("SELECT Distinct email FROM myaccount_invitation WHERE reference_id = %s AND status = 1 AND invitation_type = 2",[value]) friend = cursor12.fetchall() if friend: friends = friend[0] return render_to_response(template_name,{'a':a,'userf':row12,'friendshow':friend} , context_instance=RequestContext(request))