Django import export how to read import this file - django

Here is a picture of the import file that is to be imported
I want to read the course column but when I exclude the group column, it shows all the columns are being skipped. How can I import this file?
This is the code currently:
class courseAttendanceResource(resources.ModelResource):
Student_ID = Field(attribute='Student_ID', column_name='Student ID')
Username = Field(attribute='Username', column_name='Username')
ID_number = Field(attribute='ID_number', column_name='ID number')
Institution = Field(attribute='Institution', column_name='Institution')
Department = Field(attribute='Department', column_name='Department')
Surname = Field(attribute='Surname', column_name='Surname')
First_name = Field(attribute='First_name', column_name='First name')
Groups = Field(attribute='Groups', column_name='Groups')
P = Field(attribute='P', column_name='P')
L = Field(attribute='L', column_name='L')
E = Field(attribute='E', column_name='E')
A = Field(attribute='A', column_name='A')
Taken_sessions = Field(attribute='Taken_sessions', column_name='Taken sessions')
Points = Field(attribute='Points', column_name='Points')
Percentage = Field(attribute='Percentage', column_name='Percentage')
def get_export_headers(self):
headers = super().get_export_headers()
for i, h in enumerate(headers):
if h == 'Student ID':
headers[i] = 'Student_ID'
if h == 'Username':
headers[i] = 'Username'
if h == 'ID number':
headers[i] = 'ID_number'
if h == 'Institution':
headers[i] = 'Institution'
if h == 'Department':
headers[i] = 'Department'
if h == 'Surname':
headers[i] = 'Surname'
if h == 'First name':
headers[i] = 'First_name'
if h == 'Groups':
headers[i] = 'Groups'
if h == 'P':
headers[i] = 'P'
if h == 'L':
headers[i] = 'L'
if h == 'E':
headers[i] = 'E'
if h == 'A':
headers[i] = 'A'
if h == 'Taken sessions':
headers[i] = 'Taken_sessions'
if h == 'Points':
headers[i] = 'Points'
if h == 'Percentage':
headers[i] = 'Percentage'
return headers
class Meta:
model = courseAttendance
with open('/tmp/rows.csv') as csvfile:
# skip the first 3 lines
[next(csvfile, None) for i in range(3)]
# now load the dataset
ds = tablib.Dataset()
ds.csv = csvfile.read()
print(ds)
dataset = ds
result = resource.import_data(dataset)
import_id_fields = ('Student_ID',)
exclude = ('Course', 'Group',)
fields = ('Student_ID', 'Username', 'ID_number', 'Institution', 'Department', 'Surname', 'First_name', 'Groups',
'P', 'L', 'E', 'A', 'Taken_sessions', 'Points', 'Percentage',)
#export_order = ('Student_ID', 'Username', 'ID_number', 'Institution', 'Department', 'Surname','First_name', 'Groups', 'P', 'L', 'E', 'A','Taken_sessions', 'Points', 'Percentage')
skip_unchanged = True
report_skipped = True
I need to read the course and exclude the group column. After that i want to read the rest of the columns. I applied your answer but it gives me an error at
result = resource.import_data(dataset)

Create a Dataset before you call import_data():
Given a csv file:
Course
Group
Student ID,Username
123,abc
import tablib
with open('/tmp/rows.csv') as csvfile:
# skip the first 3 lines
[next(csvfile, None) for i in range(3)]
# now load the dataset
ds = tablib.Dataset()
ds.csv = csvfile.read()
print(ds)
Produces:
Student ID|Username
----------|--------
123 |abc
Once you have loaded your dataset, you can call the import_data() method:
result = resource.import_data(dataset)

Related

can not add or update child row, foreign key constraint failed

subscriber_package_forms = subscriber.package.form
# subscriber packages forms.
a = subscriber_package_forms.replace('[', '')
b = a.replace(']', '')
c = b.replace("'", '')
d = c.replace('''"''', '')
e = d.replace("'", '')
f = e.split(',')
#search active columns of all the packages from main database.
for frm in f:
frm = int(frm)
try:
form_columns_object = form_columns.objects.using(main_db).filter(form_id = frm).first()
except:
pass
if form_columns_object == None:
pass
else:
form_columns_dict = model_to_dict(form_columns_object)
form_instance = FormModel.objects.using(main_db).get(id = int(form_columns_dict['form']))
user_instance = User.objects.using(main_db).first() #get(username = form_columns_dict['user']) # id = form_columns_dict['id']
form_columns.objects.using(db_name).create(columns = str(form_columns_dict['columns']), form = form_instance, user=user_instance)
This code is working fine in my local setup. But i am facing a problem after committing it on server.
We have error in last line of the code i guess

If statement gives wrong output in query set

I'm getting the incorrect output of a query set when I use request.method == 'POST' and selectedaccesslevel == '#' showing as <QuerySet ['S00009']> when it's written to the database.
I believe I should be using a get since i'm expecting one value, but how do I filter my get on coid = owner.coid.coid and provide the value ?level?
I'm looking for my output for datareducecode to be 'S00009' and not <QuerySet ['S00009']>. How can I accomplish this? Below is my view...
def submitted(request):
owner = User.objects.get (formattedusername=request.user.formattedusername)
checkedlist = request.POST.getlist('report_id')
print (f"checkedlist on submitted:{checkedlist}")
access_request_date = timezone.now()
coid = User.objects.filter(coid = request.user.coid.coid).filter(formattedusername=request.user.formattedusername)
datareducecode = OrgLevel.objects.distinct().filter(coid=request.user.coid.coid)
# facilitycfo = QvDatareducecfo.objects.filter(dr_code__exact = coid, active = 1, cfo_type = 1).values_list('cfo_ntname', flat = True)
# divisioncfo = QvDatareducecfo.objects.filter(dr_code__exact = coid, active = 1, cfo_type = 2).values_list('cfo_ntname', flat = True)
# print(facilitycfo)
# print(divisioncfo)
selectedaccesslevel = request.POST.get('accesslevelid')
print (f"accesslevel:{selectedaccesslevel}")
selectedphi = request.POST.get('phi')
print (f"phi:{selectedphi}")
print (owner.coid.coid)
if request.method == 'POST' and selectedaccesslevel == '3':
datareducecode = OrgLevel.objects.filter(coid__exact = owner.coid.coid).values_list('slevel', flat = True)
print (datareducecode)
if request.method == 'POST' and selectedaccesslevel == '4':
datareducecode = OrgLevel.objects.filter(coid__exact = owner.coid.coid).values_list('blevel', flat = True)
print (datareducecode)
if request.method == 'POST' and selectedaccesslevel == '5':
datareducecode = OrgLevel.objects.filter(coid__exact = owner.coid.coid).values_list('rlevel', flat = True)
print (datareducecode)
if request.method == 'POST' and selectedaccesslevel == '6':
datareducecode = OrgLevel.objects.filter(coid__exact = owner.coid.coid).values_list('dlevel', flat = True)
print (datareducecode)
if request.method == 'POST' and selectedaccesslevel == '7':
datareducecode = OrgLevel.objects.filter(coid__exact = owner.coid.coid).values_list('f"Z{Coid}"', flat = True)
print (datareducecode)
else:
datareducecode = 'No Match on Coid'
print (datareducecode)
for i in checkedlist:
requestsave = QVFormAccessRequest(ntname = owner.formattedusername, first_name = owner.first_name, last_name = owner.last_name, coid = owner.coid.coid, facility = owner.facility, title = owner.title
,report_id = i, accesslevel_id = selectedaccesslevel, phi = selectedphi , access_beg_date = access_request_date, datareducecode = datareducecode )
requestsave.save()
# print (datareducecode)
return JsonResponse({'is_success':True})
So this seems to do the trick:
list(datareducecode)[0]

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

Allow user to sign up only for shifts that are not yet claimed?

I have a table of shifts for meals:
class mealShifts(models.Model):
Sunday = "Sunday"
Monday = "Monday"
Tuesday = "Tuesday"
Wednesday = "Wednesday"
Thursday = "Thursday"
Friday = "Friday"
Days = (
(0, "Sunday"),
(1, "Monday"),
(2, "Tuesday"),
(3, "Wednesday"),
(4, "Thursday"),
(5, "Friday"),
(6, "Saturday")
)
Breakfast = "Breakfast"
Dinner = "Dinner"
Meals = (
(Breakfast, "Breakfast"),
(Dinner, "Dinner"),
)
Chef = "Chef"
Sous_Chef = "Sous-Chef"
KP ="KP"
Shifts = (
(Chef, "Chef"),
(Sous_Chef, "Sous_Chef"),
(KP, "KP"),
)
assigned = models.BooleanField(default=False)
day = models.CharField(max_length = 1, choices=Days)
meal = models.CharField(max_length = 10, choices=Meals)
shift = models.CharField(max_length = 10, choices=Shifts, default=KP)
camper = models.OneToOneField(User)
class Meta:
unique_together = ("day", "meal", "shift")
def __str__(self):
return '%s %s %s %s'%(self.day, self.meal, self.shift, self.camper)
And here is my view:
#login_required(login_url='login.html')
def signup(request):
sundayShifts = mealShifts.objects.filter(day="Sunday")
mondayShifts = mealShifts.objects.filter(day="Monday")
#the rest of the shifts will go here
username = None
context = RequestContext(request)
if request.method == 'POST':
form = MealForm(request.POST)
if form.is_valid():
shift = form.save(commit=False)
shift.camper = request.user
shift.save()
return redirect('signup')
else:
print form.errors
else:
form = MealForm()
return render_to_response('signup.html',
RequestContext(request, {'form':form,'username':username, 'sundayShifts':sundayShifts, 'mondayShifts':mondayShifts},))
There are 42 possible meal shifts. How can I create a view that will display only the shift choices that nobody has taken - the possible combinations which aren't yet in the database?
You could do something like:
import itertools
# Ideally, reuse these from the model some how
day_choices = range(0, 6)
meal_choices = [Breakfast, Dinner]
shift_choices = [Chef, Sous_Chef, KP]
shift_options = itertools.product(day_choices, meal_choices, shift_choices)
avaliable_shift_choices = filter(
lambda option: not mealShifts.objects.filter(day=options[0], meal=option[1], shift=option[2]).exists(),
shift_options
)
This will give you combinations of day, meal and shift not currently in the db, without loading too much data, or being too expensive on the db.

Django - POST request not retrieved correctly

I'm working on a inventory control in Django and i want a form to control the action that will be made. If a record for the product already exist, it should update the quantity. If it doesn't exist, it should create the record for it. Besides that, one form field will have three choices. One will add the form value to que product quantity, other will subtract and another one will change to the value in the form.
The model is quite big, because i set some choices for the form fields. There it is:
from django.db import models
from django import forms
from django.forms import ModelForm
class Produto(models.Model):
CAMISA = "CM"
QUADRO = "QD"
CANECA = 'CN'
ESCOLHAS_PRODUTO = (
(CAMISA, 'Camisa'),
(QUADRO, 'Quadro'),
(CANECA, 'Caneca'),
)
tipo = models.CharField(max_length = 40,
choices=ESCOLHAS_PRODUTO,
default=CAMISA)
class Camisa(Produto):
MASCULINA = 'MA'
FEMININA_BASICA = 'FB'
FEMININA_GOLA_V = 'FV'
INFANTIL = 'IN'
MODELO_CAMISA = (
(MASCULINA, 'Masculina'),
(FEMININA_BASICA, 'Feminina Basica'),
(FEMININA_GOLA_V, 'Feminina Gola V'),
(INFANTIL, 'Infantil'),
)
modelo = models.CharField(max_length = 50,
choices=MODELO_CAMISA,
)
AMARELA = 'AM'
AZUL_CLARO = 'AC'
AZUL_ESCURO = 'AE'
BRANCA = 'BR'
CINZA = 'CI'
LARANJA = 'LA'
MARFIM = 'MA'
ROSA = 'RO'
PRETA = 'PR'
VERDE_MUSGO = 'VM'
VERMELHA = 'VR'
CORES_CAMISA = (
(AMARELA, 'Amarela'),
(AZUL_CLARO, 'Azul Claro'),
(AZUL_ESCURO, 'Azul Escuro'),
(BRANCA, 'Branca'),
(CINZA, 'Cinza'),
(LARANJA, 'Laranja'),
(MARFIM, 'Marfim'),
(ROSA, 'Rosa'),
(PRETA, 'Preta'),
(VERDE_MUSGO, 'Verde Musgo'),
(VERMELHA, 'Vermelha'),
)
cor = models.CharField(max_length = 40,
choices=CORES_CAMISA,
)
TAMANHO_P = 'TP'
TAMANHO_M = 'TM'
TAMANHO_G = 'TG'
TAMANHO_GG = 'GG'
TAMANHO_XG = 'XG'
TAMANHO_02_ANOS = '02'
TAMANHO_04_ANOS = '04'
TAMANHO_06_ANOS = '06'
TAMANHO_08_ANOS = '08'
TAMANHO_10_ANOS = '10'
TAMANHO_12_ANOS = '12'
TAMANHO_14_ANOS = '14'
TAMANHO_CAMISA = (
(TAMANHO_P, 'P'),
(TAMANHO_M, 'M'),
(TAMANHO_G, 'G'),
(TAMANHO_GG, 'GG'),
(TAMANHO_XG, 'XGG'),
(TAMANHO_02_ANOS, '2 Anos'),
(TAMANHO_04_ANOS, '4 Anos'),
(TAMANHO_06_ANOS, '6 Anos'),
(TAMANHO_08_ANOS, '8 Anos'),
(TAMANHO_10_ANOS, '10 Anos'),
(TAMANHO_12_ANOS, '12 Anos'),
(TAMANHO_14_ANOS, '14 Anos'),
)
tamanho= models.CharField(max_length = 50,
choices=TAMANHO_CAMISA,
)
quantidade = models.IntegerField()
def __unicode__(self):
return self.modelo
class CamisaForm(ModelForm):
ADICIONAR = 'ADC'
REDUZIR = 'RED'
ALTERAR = 'ALT'
ACOES = (
(ADICIONAR, 'Adicionar Quantidade'),
(REDUZIR, 'Reduzir Quantidade'),
(ALTERAR, 'Alterar para Quantidade'),
)
acoes = forms.ChoiceField(
choices=ACOES,
)
class Meta:
model = Camisa
And the following view:
def index(request):
produtos_estoque = Camisa.objects.all()
template = 'estoque/index.html'
modelos_camisa = {'MA' : 'Masculina Basica','FB' : 'Feminina Basica','FV' : 'Feminina Gola V','IN' : 'Infantil' }
if request.method == 'POST':
form = CamisaForm(request.POST)
if form.is_valid():
try:
produto_atualizar = Camisa.objects.get(modelo = request.POST['modelo'], cor = request.POST['cor'], tamanho = request.POST['tamanho'])
if request.POST['acoes'] == 'ADC':
produto_atualizar.quantidade = produto_atualizar.quantidade + request.POST['quantidade']
elif request.POST['acoes'] == 'RED':
produto_atualizar.quantidade = produto_atualizar.quantidade - request.POST['quantidade']
elif request.POST['acoes'] == 'ALT':
produto_atualizar.quantidade = request.POST['quantidade']
produto_atualizar.save()
except:
produto_atualizar = form.save()
return HttpResponseRedirect('')
else:
form = CamisaForm()
return render_to_response(template, { 'form': form, 'produtos_estoque': produtos_estoque,
'modelos_camisa' : modelos_camisa.iteritems(), }, context_instance=RequestContext(request))
But what is happening is that the form is just creating another record for the product, even if it already exists. Not sure if the rest of the model is important for this question, will post it if necessary. Can somebody help me on this one? Thanks
Please post the Model this is acting on - it will have some useful information, like constraints or lack thereof etc. OK cool, no unique constraints in there causing insert violations.
First thing I would recommend is using the forms cleaned_data to access form values instead of the raw POST data, form.is_valid() does a lot of work to process the raw data into acceptable inputs for Model data.
Second thing is that except clause will catch ANY exception which I suspect is your problem... Something else is going wrong which is creating the new record in the except clause. Be specific, like except Camisa.DoesNotExist:
Third thing is to put those constants on the Model so you can reference them from the Form and View instead of literal strings. This is just a cleanliness / code style recommendation.
A little cleanup might look like:
MODELOS_CAMISA = {'MA' : 'Masculina Basica','FB' : 'Feminina Basica','FV' : 'Feminina Gola V','IN' : 'Infantil' }
def index(request):
produtos_estoque = Camisa.objects.all()
if request.method == 'POST':
form = CamisaForm(request.POST)
if form.is_valid():
try:
produto_atualizar = Camisa.objects.get(modelo=form.cleaned_data.get('modelo'), cor=form.cleaned_data.get('cor'), tamanho=form.cleaned_data.get('tamanho'))
quantidade = form.cleaned_data.get('quantidade')
acoes = form.cleaned_data.get('acoes')
if acoes == Camisa.ADC:
produto_atualizar.quantidade = produto_atualizar.quantidade + quantidade
elif acoes == Camisa.RED:
produto_atualizar.quantidade = produto_atualizar.quantidade - quantidade
elif acoes == Camisa.ALT:
produto_atualizar.quantidade = quantidade
produto_atualizar.save()
except Camisa.DoesNotExist:
produto_atualizar = form.save()
return HttpResponseRedirect('')
else:
form = CamisaForm()
return render_to_response('estoque/index.html', { 'form': form, 'produtos_estoque': produtos_estoque,
'modelos_camisa' : MODELOS_CAMISA.iteritems(), }, context_instance=RequestContext(request))
(Sorry for any grammatical errors, my Portuguese is not great)
That should be enough to get you started, if you add more information I can edit and elaborate my answer. Good luck!