invalid literal for int() with base 10: '' when creating object - python

I'm trying to read from a CSV file and create an object in Django (1.9, Py 3.5) but I'm getting this error, no matter what I change the field to
invalid literal for int() with base 10: ''
And the line is:
other = row['Other']
site = Site.objects.create(consolidated_financials = row['Consolidated financials'],
type = Type.objects.get_or_create(name=row['Type'])[0],
tier1_business = Business.objects.get_or_create(tier=1, name=row['Tier-1 business'])[0],
tier2_business = Business.objects.get_or_create(tier=2, name=row['Tier-2 business'])[0],
tier3_business = Business.objects.get_or_create(tier=2, name=row['Tier-3 business'])[0],
site_name = row['Site Name'],
site_id = row['Site ID'],
region = Region.objects.get_or_create(name=row['Region'])[0],
country = Country.objects.get_or_create(name=row['Country'], region=Region.objects.get_or_create(name=row['Region'])[0])[0],
city = City.objects.get_or_create(name=row['City'], country=Country.objects.get_or_create(name=row['Country'], region=Region.objects.get_or_create(name=row['Region'])[0])[0])[0],
site_type = SiteType.objects.get_or_create(name=row['Type of site?'])[0],
remote_site = row['Remote site?'],
finance_manager_name = row['Finance Manager Name'],
finance_manager_sso = row['Finance Manager SSO'],
quarter = row['Quarter'],
revenue = row['Revenue'],
supply_chain_manager_name = row['Supply Chain Manager Name'],
supply_chain_manager_sso = row['Supply Chain Manager SSO'],
product_lines = row['Product Lines'],
manufacturing_processes = row['Manufacturing Processes'],
factory_utilization = row['Factory Utilization'],
fte = row['FTE'],
hourly = row['Hourly'],
salaried = row['Salaried'],
other = row['Other']
)
The Site model:
class Site(models.Model):
"""
Model for a site entry
#author: Leonardo Pessoa
#since: 05/09/2016
"""
from decimal import Decimal
consolidated_financials = models.BooleanField()
type = models.ForeignKey(Type)
tier1_business = models.ForeignKey(Business, limit_choices_to = {'tier': 1}, related_name='%(class)s_tier1')
tier2_business = models.ForeignKey(Business, limit_choices_to = {'tier': 2}, related_name='%(class)s_tier2')
tier3_business = models.ForeignKey(Business, limit_choices_to = {'tier': 3}, related_name='%(class)s_tier3')
site_name = models.CharField(max_length = 150, unique=True)
site_id = models.IntegerField()
region = models.ForeignKey(Region)
country = models.ForeignKey(Country)
city = models.ForeignKey(City)
site_type = models.ForeignKey(SiteType)
remote_site = models.BooleanField()
finance_manager_name = models.CharField(max_length = 50)
finance_manager_sso = models.IntegerField()
quarter = models.DecimalField(max_digits = 12, decimal_places = 2, default=Decimal('0.0'))
revenue = models.DecimalField(max_digits = 12, decimal_places = 2, default=Decimal('0.0'))
supply_chain_manager_name = models.CharField(max_length = 50, default='')
supply_chain_manager_sso = models.IntegerField(default=000000000)
product_lines = models.CharField(max_length = 100, default='')
manufacturing_processes = models.TextField(max_length = 500, default='')
factory_utilization = models.DecimalField(max_digits = 5, decimal_places = 2, default=Decimal('0.0'))
fte = models.IntegerField()
hourly = models.IntegerField()
salaried = models.IntegerField()
other = models.TextField(max_length = 500, default='')
ges_id = models.CharField(max_length = 20)
latitude = models.DecimalField(max_digits = 10, decimal_places=7, default=Decimal('0.0'))
longitude = models.DecimalField(max_digits = 10, decimal_places=7, default=Decimal('0.0'))
The row:
row
{'City': 'xxxxxxx',
'Consolidated financials': 'True',
'Country': 'Argentina (AR)',
'FTE': '',
'Factory Utilization': '',
'Finance Manager Name': '',
'Finance Manager SSO': '',
'Hourly': '',
'Manufacturing Processes': '',
'Other': '',
'Product Lines': '',
'Quarter': '',
'Region': 'Latin America',
'Remote site?': 'True',
'Revenue': '',
'Salaried': '',
'Site ID': '12312',
'Site Name': 'xxxxxxxxx',
'Supply Chain Manager Name': '',
'Supply Chain Manager SSO': '',
'Tier-1 business': 'xxxxxxxxxx',
'Tier-2 business': 'xxxxxxxxxxxxx',
'Tier-3 business': 'Latin America',
'Type': 'xxxxxx xxxxx',
'Type of site?': 'Other'}
I know the code has a lot of room for performance optimization but I just want to prove the functionality first.
Thanks!

The problem is that your Site model is expecting other to be an int (does the model have other = IntegerField or similar?), and you're providing an empty string. The easiest fix is to change row['Other'] to row['Other'] or 0
If you know that you're going to get non-numeric values as a general rule, then you could add basic logic to test for non-digits, or update your IntegerField to something which can accept text. A list of valid Django fields can be found here.
# An example of conditional logic to test for a non-number and use 0 if so
other = row['Other'] if row['Other'] and row['Other'].isdigit() else 0
Edit
Looking at your model, the issue is probably not with the Other field, but there are typing problems nevertheless. For example Supply Chain Manager SSO is supposed to be an int, but you are definitely passing a ''.

Related

How can i attach django models data as Excel file and send it as mail with SMTP

i have some data in django models and i want to make excel file from that data and attach it in SMTP as file and send it to target user.
i am also using django-import-export to export the excel files .but in this case i want to attach the file in email.
Model
class FinalBill(models.Model):
shipDate = models.DateField(blank = True, null = True, auto_now=False, auto_now_add=False)
customerReference = models.CharField(max_length = 200, blank = True, null = True)
customerConfirmation = models.CharField(max_length = 200, blank = True, null = True)
deliveryConfirmation = models.CharField(max_length = 200, blank = True, null = True)
address = models.CharField(max_length = 200, blank = True, null = True)
service = models.CharField(max_length = 200, blank = True, null = True)
weight = models.FloatField(blank = True, null = True)
pricingZone = models.CharField(max_length = 200, blank = True, null = True)
uspsCompRate = models.FloatField(blank = True, null = True)
charges = models.FloatField(blank = True, null = True)
surcharges = models.FloatField(blank = True, null = True)
totalSavings = models.FloatField(blank = True, null = True)
totalCharges = models.FloatField(blank = True, null = True)
customerID = models.CharField(max_length = 200)
is_exported = models.BooleanField(default=False)
exported_date = models.DateField(blank = True, null = True, auto_now=False, auto_now_add=False)
def __str__(self):
return str(self.deliveryConfirmation)
Utills.py
def send_bill_on_mail(mailerID):
customerBill = FinalBill.objects.filter(customerID=mailerID, is_exported=False)
dataset = Bills().export(customerBill)
mail_subject = "Subject Name"
message = "Test Email Message"
to_email = "xyz#gmail.com"
file = "file"
mail = EmailMessage(mail_subject, message, settings.EMAIL_HOST_USER, [to_email])
mail.attach(file.name, file.read(), file.content_type)
mail.send()
def export_data_to_excel(mailerID) -> None:
excelfile = BytesIO()
workbook = Workbook()
workbook.remove(workbook.active)
worksheet = workbook.create_sheet(title='Title Name', index=1)
bill_queryset = Bills.objects.filter(cus_id=mailerID, is_exported=False)
columns = ['Date', 'Reference', 'Confirmation', 'Confirmation', 'Address', 'Service', 'Weight', 'Pricing Zone', 'UspsRate', 'Charges', 'Sur Charges', 'Total Savings', 'Total Charges', 'Customer ID']
row_num = 1
# Assign the titles for each cell of the header
for col_num, column_title in enumerate(columns, 1):
cell = worksheet.cell(row=row_num, column=col_num)
cell.value = column_title
cell.alignment = Alignment(horizontal='center', vertical='center', wrap_text=False)
cell.font = Font(bold=True)
# Iterate through all coins
for _, bill in enumerate(bill_queryset, 1):
row_num += 1
# Define the data for each cell in the row
row = [
bill.shipDate,
bill.customerReference,
bill.customerConfirmation,
bill.deliveryConfirmation,
bill.address,
bill.service,
bill.weight,
bill.pricingZone,
bill.uspsCompRate,
bill.charges,
bill.surcharges,
bill.totalSavings,
bill.totalCharges,
bill.customerID,
]
# Assign the data for each cell of the row
for col_num, cell_value in enumerate(row, 1):
cell = worksheet.cell(row=row_num, column=col_num)
cell.value = cell_value
cell.protection = Protection(locked=True)
workbook.save(excelfile)
mail_subject = f'Invoice {mailerID} on {date.today()}'
message = ""
to_email = "xyz#gmail.com"
message = EmailMessage(mail_subject, message, settings.EMAIL_HOST_USER, [to_email])
message.attach(f'Invoice {mailerID}.xlsx', excelfile.getvalue(), 'application/vnd.ms-excel')
message.send()
django-tables2 can help you in this, you create your table as Class which will be fed from your data and then you can export the table to XLS document and then you can email to the user.
References:
Get Started with django-tables2
Exporting Data

Django Matching query don't exist in AddProduct.objects.get(Name=productname[i])

I have a model AddProduct and StockIn. When a new stock are purchased from dealer than all purchased product are get added in StockIn model. And Existing products are updated in AddProduct model.
My AddProduct models are as follows
class AddProduct(models.Model):
Name = models.CharField(max_length=120,verbose_name="name")
Description = models.CharField(max_length=120, verbose_name="description")
Unit = models.ForeignKey(Unit,on_delete=models.CASCADE,max_length=150,verbose_name='unit')
purchaseRate = models.DecimalField(max_digits=10, decimal_places=3,verbose_name="purchase rate")
AvgRate = models.DecimalField(max_digits=10, decimal_places=3,verbose_name="avg rate")
OpnStock = models.DecimalField(max_digits=10, decimal_places=3,verbose_name="Opening stock")
ClosingStock = models.DecimalField(max_digits=10, decimal_places=3,verbose_name="closing stock")
StoreLocation = models.CharField(max_length=120,verbose_name="store location")
MinStock = models.DecimalField(max_digits=10, decimal_places=3,verbose_name="minimum stock")
ReOrder = models.DecimalField(max_digits=10, decimal_places=3,verbose_name="reorder")
MaxStock = models.DecimalField(max_digits=10, decimal_places=3,verbose_name="maxstock")
Group = models.ForeignKey(ProductGroup,on_delete=models.CASCADE,max_length=150,verbose_name='productgroup')
CGST = models.DecimalField(max_digits=10, decimal_places=3,verbose_name="CGST")
SGST = models.DecimalField(max_digits=10, decimal_places=3,verbose_name="SGST")
IGST = models.DecimalField(max_digits=10, decimal_places=3,verbose_name="IGST")
Validity = models.IntegerField(verbose_name="validity")
Updated = models.DateTimeField(auto_now=True)
while my StockIn model are as follows
class StockIN(models.Model):
GrnNo = models.IntegerField(verbose_name="GrnNo")
Date = models.DateTimeField(default=timezone.now)
Supplier = models.ForeignKey(AddSupplier,on_delete=models.CASCADE,max_length=150,verbose_name='supplier')
InvoiceNo = models.IntegerField(verbose_name="invoice No")
InvoiceDate = models.DateTimeField(default=timezone.now, verbose_name="Invoice Date")
ProductName = models.CharField(max_length=120,verbose_name="productName")
Quantity = models.IntegerField(verbose_name="quantity")
Unit = models.ForeignKey(Unit,on_delete=models.CASCADE,max_length=150,verbose_name='unit')
Rate = models.CharField(max_length=120,verbose_name="rate")
Value = models.CharField(max_length=120,verbose_name="value")
DisPer = models.CharField(max_length=120,verbose_name="disper")
DisValue = models.CharField(max_length=120,verbose_name="disvalue")
Taxable = models.CharField(max_length=120,verbose_name="taxable")
CGSTPER = models.CharField(max_length=120,verbose_name="cgstper")
CGST = models.CharField(max_length=120,verbose_name="cgst")
SGSTPER = models.CharField(max_length=120,verbose_name="sgstper")
SGST = models.CharField(max_length=120,verbose_name="sgst")
IGSTPER = models.CharField(max_length=120,verbose_name="igstper")
IGST = models.CharField(max_length=120,verbose_name="igst")
NetAmt = models.CharField(max_length=120,verbose_name="netamt")
I recieving a list of product details from template. So after submiting the request i am getting the result of print(request.POST) like this.
<QueryDict: {'csrfmiddlewaretoken': ['BKetQA2dIzgRlkLmIJGsZbWB3nzDiQxgR9FHnzN9lmDr86mdEJygUZJ08TORmU3N'], 'GrnNo': ['4'], 'Date': ['2022-03-20'], 'initial-Date': ['2022-03-20 06:09:47'], 'Supplier': ['2'], 'InvoiceNo': ['4444'], 'InvoiceDate': ['2022-03-20'], 'initial-InvoiceDate': ['2022-03-20 06:09:47'], 'productname': ['Safety shoes ','welder'], 'uom': ['0','0'], 'quantity': ['5','6'], 'unit': ['1','1'], 'rate': ['329','220'], 'value': ['1645','1320'], 'disper': ['2','2'], 'disvalue': ['32.9','20.2'], 'taxable': ['0','0'], 'cgstper': ['4','4'], 'cgstvalue': ['64.484','62.2'], 'sgstper': ['4','4'], 'sgstvalue': ['64.484','62.22'], 'igstper': ['4','4'], 'igstvalue': ['64.484','62.22'], 'netamt': ['1612.164.48464.48464.4840','1226.255242'], 'example_length': ['10']}>
This is my purchaseView function where i am doing query and get error as AddProduct matching query does not exist.
def PurchaseView(request):
stockinform = StockInForm()
product = AddProduct.objects.all()
unit = {}
unitobj = Unit.objects.all()
for obj in unitobj:
unit[obj.id]=f'{obj.Name}'
print(request.POST)
if request.method == 'POST':
grnno = request.POST.getlist('GrnNo')
date = request.POST.getlist('Date')
supplier = request.POST.getlist('Supplier')
supplierinstance = AddSupplier.objects.get(id=supplier[0])
invoiceno = request.POST.getlist('InvoiceNo')
invoicedate = request.POST.getlist('InvoiceDate')
productname = request.POST.getlist('productname')
uom = request.POST.getlist('uom'),
quantity = request.POST.getlist('quantity')
unitname = request.POST.getlist('unit')
rate = request.POST.getlist('rate')
value = request.POST.getlist('value')
disper = request.POST.getlist('disper')
disvalue = request.POST.getlist('disvalue')
taxable = request.POST.getlist('taxable')
cgstper = request.POST.getlist('cgstper')
cgstvalue = request.POST.getlist('cgstvalue')
sgstper = request.POST.getlist('sgstper')
sgstvalue = request.POST.getlist('sgstvalue')
igstper = request.POST.getlist('igstper')
igstvalue = request.POST.getlist('igstvalue')
netamt = request.POST.getlist('netamt')
productlen = len(productname)
for i in range(0,productlen):
unitinstance = Unit.objects.get(id=unitname[i])
print(productname[i])
productupdate = AddProduct.objects.get(Name=productname[i])
StockIN.objects.create(GrnNo=grnno[0],
Date=date[0],
Supplier=supplierinstance,
InvoiceNo=invoiceno[0],
InvoiceDate=invoicedate[0],
ProductName=productname[i],
Quantity=quantity[i],
Unit=unitinstance,
Rate=rate[i],
Value=value[i],
DisPer=disper[i],
DisValue=disvalue[i],
Taxable=taxable[i],
CGSTPER=cgstper[i],
CGST=cgstvalue[i],
SGSTPER=sgstper[i],
SGST=sgstvalue[i],
IGSTPER=igstper[i],
IGST=igstvalue[i],
NetAmt=netamt[i])
productupdate.OpnStock = 0
productupdate.ClosingStock = quantity[i]
productupdate.purchaseRate = rate[i]
productupdate.CGST = cgstper[i]
productupdate.SGST = sgstper[i]
productupdate.IGST = igstper[i]
productupdate.save()
return render(request, "stock/purchase.html",{"form":stockinform,"products":product,"unit":unit})
When i am testing django shell then all things working fine.
but after submiting the form in template this is not working. I don't know why. Please help me bro
Since you're querying your model inside loop i will suggest inspecting values in a log or console when error comes up also i will suggest using StockIN.objects.bulk_create() instead of creating items instead in loop

Instance Error On Foreign Key Field Django

Im stumped and need help on my function.
I have two tables student and student information. Student information is all guardian information of that student. I separated this data from the main student table so you can add as many guardians as you want to a students file with new records. The error I'm getting is as followed.
Cannot assign "'1'": "StudentInformation.studentpsid" must be a "Student" instance.
Attached you will see my code. Studentpsid in student information is a foreign key from student.
def ImportStudentGuardian(request):
AuthTokenP(request)
print("Getting student guardian data from SIS for K-8")
#Pulls K-8 Guardians
url = "removed for posting"
payload = {}
token = APIInformation.objects.get(api_name="PowerSchool")
key = token.key
headers = {'Authorization': 'Bearer {}'.format(key)}
response = requests.request("GET", url, headers=headers, data = payload)
encode_xml = response.text.encode('utf8')
xml_string = ET.fromstring(encode_xml)
students = xml_string.findall("student")
for student in students:
#XML Values
psid = student.find("id").text
try:
mother = student.find("contact").find("mother").text
except Exception:
mother = ""
try:
father = student.find("contact").find("father").text
except Exception:
father = ""
if Student.objects.filter(studentpsid=psid).exists():
print("Accessing guardian information.")
m = StudentInformation.objects.create(studentpsid=psid,guardian_name = mother, relation = "Mom") <---- Function Fails here
print("Record doesn't exist for mom, creating record.")
m.save()
d= StudentInformation.objects.create(studentpsid=psid,guardian_name = father, relation = "Dad")
print("Record doesn't exist for dad, creating record.")
d.save()
return ("Updated Guardian Information ")
Model
class Student(models.Model):
studentpsid= models.CharField(primary_key = True , default = "", max_length = 50, unique = True)
student_name = models.CharField(max_length = 50)
first_name = models.CharField(max_length = 50, default = "")
last_name = models.CharField(max_length = 50,default = "")
gender = models.CharField(max_length = 1,default = "")
student_grade = models.CharField(max_length = 2, default = "")
home_room = models.CharField(max_length = 5, default = "")
student_enrollment = models.CharField(max_length = 2, default = "")
school_number = models.CharField(max_length = 15, default = "")
email = models.EmailField(default = "")
projected_graduation_year = models.CharField(max_length = 4, default = "")
counseling_goal = models.TextField(max_length = 255)
class_name = models.ManyToManyField(TeacherClass)
image = models.ImageField(default ="default.png", upload_to ='student_pics')
# Guardian Information For Student
class StudentInformation(models.Model):
studentpsid = models.ForeignKey(Student,on_delete = models.CASCADE, default = "" ,)
guardian_name = models.CharField(max_length = 50, default = "")
RELATION_CHOICES = [
(0, 'None'),
(1, 'Mom'),
(2, 'Dad'),
(3, 'Other'),
]
relation = models.PositiveSmallIntegerField(choices = RELATION_CHOICES,)
guardian_cell = models.CharField(max_length = 12, default = "")
guardian_email = models.EmailField(max_length = 80,blank = True, default = "")
prefered_contact = models.BooleanField(default = False, blank = True)
DAY_CHOICES = [
(0, 'None'),
(1, 'Monday'),
(2, 'Tuesday'),
(3, 'Wednesday'),
(4, 'Thursday'),
(5, 'Friday'),
]
day_of_week = models.PositiveSmallIntegerField(choices = DAY_CHOICES, default = 0 )
time = models.CharField(max_length= 7, default = "", blank = True)
While creating a record with the foreign key relation, and instance of the related table should be provided, so the table can maintain a relationship for that particular record.
Get the instance of the Student table with the given psid and use that while creating the StudentInformation record
EDIT : Included the part for creating the record only if mother and father values are available.
for student in students:
#XML Values
psid = student.find("id").text
try:
psid_obj = Student.objects.get(studentpsid=psid) #(pk = psid) also works as the field is primary key
try:
mother = student.find("contact").find("mother").text
m = StudentInformation.objects.create(studentpsid=psid_obj,guardian_name = mother, relation = "Mom")
m.save()
except Exception as err1:
print "Error at Mom", str(err1)
try:
father = student.find("contact").find("father").text
d= StudentInformation.objects.create(studentpsid=psid_obj,guardian_name = father, relation = "Dad")
d.save()
except Exception as err2:
print "Error at Dad",str(err2)
except:
print "Student Record Not found"
As the error says, you are assigning a char data type to the ForeignKey field.
You should first get the instance of that Student, and then assign it to your StudentInformation object, like this:
if Student.objects.filter(studentpsid=psid).exists():
print("Accessing guardian information.")
student = Student.objects.get(pk=psid) # this will fail if the student doesn't exist
m = StudentInformation.objects.create(studentpsid=student,guardian_name = mother, relation = "Mom") <---- Function Fails here
print("Record doesn't exist for mom, creating record.")
m.save()
d= StudentInformation.objects.create(studentpsid=student,guardian_name = father, relation = "Dad")
print("Record doesn't exist for dad, creating record.")
d.save()
return ("Updated Guardian Information ")

In Odoo 10,how can I specify a data in create_date,create_uid,instead of value in system,when I use method named 'create' to create a record

I create new record with the method named create() in local database with data pulled away from remote database.As we all know,there are four normal fields in Odoo such as create_date,write_date,create_uid,write_uid.I want these data to be in a remote databaseļ¼Œbut when I use method named create() to create the record,these data are the data at the time of local creation and not the remote data.
For example,in remote database,the creat_date is '2019-10-11',I can't change the value that is finally written to the local database even if I pass the value of the remote database into the dictionary.Finally,the value of field named create_date is '2019-12-03' rather than '2019-10-11'.The '2019-12-03' is the date now.The situation is similar for other fields such as write_date,create_uid,write_uid.
Please help me,thanks to everyone who thought about this question.
Following is my code.
The Class Model
class ReportRentalIncomeFromProperty(models.Model):
_name = 'report.rental.income.from.property'
_description = 'The report about the income from property rental'
_order = 'product_id, start_date'
# create_date = fields.Datetime('Created on')
create_uid = fields.Char('Created by')
# write_date = fields.Datetime('Last Modified on')
write_uid = fields.Char('Last Contributor')
product_id = fields.Many2one('product.product', 'Property House')
area_id = fields.Many2one('res.country.area', 'City')
district_id = fields.Many2one('res.country.district', 'District')
town_id = fields.Many2one('res.country.town', 'Town')
road_name = fields.Char('Road')
start_date = fields.Date('Start Date')
end_date = fields.Date('End Date')
should_pay = fields.Float('Should Pay')
real_pay = fields.Float('Real Pay')
balance_pay = fields.Float('Balance Pay')
rental_compliance_rate = fields.Float('Rental Compliance Rate(%)', group_operator="avg")
company_id = fields.Many2one('res.company', string='Company')
parent_company_id = fields.Many2one('res.company', related='company_id.parent_id', store=True,
string='Parent Company')
actual_business = fields.Many2many(
'rh.commercial.activities',
'house_rental_rent_income_business_db',
'actual_business_id',
'commercial_activities_id',
string='Actual business')
The function to pull away remote data to create new record in local database.
#api.multi
def synchronization_contract_performance_rate(self):
self.env['report.rental.income.from.property'].search([]).unlink()
product_dict = {}
A_product = self.env['product.product'].search([])
for a in A_product:
product_dict[a.name] = a.id
activities_dict = {}
D_activities = self.env['rh.commercial.activities'].search([])
for d in D_activities:
activities_dict[d.name] = d.id
address_dict = {}
i = 0
address_model_list = ['res.country.area', 'res.country.district', 'res.country.town']
address_field_list = ['area_id', 'district_id', 'town_id']
for addr in address_model_list:
C_address = self.env[addr].search([])
addr_dict = {}
for c in C_address:
addr_dict[c.name] = c.id
address_dict[i] = addr_dict
i += 1
record_list_1 = self.company_recursive_func()
for list_1 in record_list_1:
database = list_1[0]
link_url = list_1[1]
if link_url.startswith('http://'):
_uri = link_url.replace('http://', '')
my_odoo = odoorpc.ODOO(_uri, port=48080)
if link_url.startswith('https://'):
_uri = link_url.replace('https://', '')
my_odoo = odoorpc.ODOO(_uri, port=443, protocol='jsonrpc+ssl')
username = list_1[2]
password = list_1[3]
my_odoo.login(database, username, password)
company_id = list_1[4]
company_code = list_1[5]
product_actual_business_dict = {}
A_product_actual_business_ids = my_odoo.env['product.product'].search([])
A_product_actual_business = my_odoo.execute('product.product', 'read', A_product_actual_business_ids,
['actual_business'])
for a in A_product_actual_business:
name_list = []
for b in my_odoo.execute('rh.commercial.activities', 'read', a.get('actual_business'), ['name']):
name_list.append(b.get('name'))
product_actual_business_dict[a.get('id')] = name_list
remote_ids = my_odoo.env['report.rental.income.from.property'].search([])
remote_data_dict = my_odoo.execute('report.rental.income.from.property', 'read', remote_ids, ['product_id',
'start_date',
'create_date',
'create_uid',
'write_date',
'write_uid',
'end_date',
'should_pay',
'balance_pay',
'real_pay',
'rental_compliance_rate',
'area_id',
'road_name',
'district_id',
'town_id'])
for data in remote_data_dict:
remote_product_name = data.get('product_id')[1]
product_id = product_dict.get(remote_product_name + '(' + company_code + ')',
None)
if product_id:
i = 0
address_id_list = []
for address_field in address_field_list:
if data.get(address_field):
remote_address_name = data.get(address_field)[1]
local_address_id = address_dict[i].get(remote_address_name, None)
address_id_list.append(local_address_id)
else:
address_id_list.append(None)
i += 1
ids_list = []
find_names = product_actual_business_dict.get(data.get('product_id')[0])
for find_name in find_names:
id = activities_dict.get(find_name, None)
if id:
ids_list.append(id)
value = {
'product_id': product_id,
'area_id': address_id_list[0],
'district_id': address_id_list[1],
'town_id': address_id_list[2],
'road_name': data['road_name'],
'start_date': data['start_date'],
'end_date': data['end_date'],
'should_pay': data['should_pay'],
'real_pay': data['real_pay'],
'create_date': data['create_date'],
'create_uid': data['create_uid'][1],
'write_date': data['write_date'],
'write_uid': data['write_uid'][1],
'balance_pay':data['balance_pay'],
'rental_compliance_rate': data['rental_compliance_rate'],
'company_id': company_id,
'actual_business': [(6, 0, ids_list)]
}
self.env['report.rental.income.from.property'].create(value)
my_odoo.logout()
You can change standart odoo fields after you create your record with sql query
property_id = self.env['report.rental.income.from.property'].create(value)
self.env.cr.execute("UPDATE report_rental_income_from_property SET create_date='%s', create_uid=%s, write_date='%s', write_uid=%s WHERE id=%s" %
(value['create_date'], value['create_uid'], value['write_date'], value['write_uid'], property_id))

invalid literal for int() with base 10: 'string name'

I am making an API module which saves weather data to my Django database by running a single Django management command, which retries all the data from a source API. I've created a model 'weather data' which has all the required datatypes. I've a management command written which directly saves data to my database.
The snippet of management command and models.py is shown below.
def handle(self,*args,**kwargs):
for city in input_file:
city_name = city.strip()
print(city_name)
full_api_url = api + city_name + '&mode=json&units=' + unit + '&APPID=' + user_api
full_wet_url = weather_api + city_name + '&mode=json&units=' + unit + '&APPID=' + user_api
try:
data = requests.get(full_api_url).json()
dta = requests.get(full_wet_url).json()
city_id = dta["id"]
longitude = dta["coord"]["lon"]
latitude= dta["coord"]["lat"]
for dt in data["list"]:
temp = dt["main"]["temp"]
temp_min = dt["main"]["temp_min"]
temp_max = dt["main"]["temp_max"]
pressure = dt["main"]["pressure"]
sea_level = dt["main"]["sea_level"]
grnd_level = dt["main"]["grnd_level"]
humidity = dt["main"]["humidity"]
weather = dt["weather"][0]
main = weather["main"]
description = weather["description"]
clouds = dt["clouds"]["all"]
wind_speed = dt["wind"]["speed"]
wind_deg = dt["wind"]["deg"]
dt_txt = dt["dt_txt"]
wd = weatherdata(city_name,city_id,latitude,longitude,dt_txt,temp,temp_min,temp_max,pressure,sea_level,grnd_level,humidity,main,description,clouds,wind_speed,wind_deg).save()
print ("Success")
except Exception as e:
print (e)
pass
class weatherdata(models.Model):
city_name = models.CharField(max_length = 80)
city_id = models.IntegerField(default=0)
latitude = models.FloatField(null=True , blank=True)
longitude = models.FloatField(null=True , blank=True)
dt_txt = models.DateTimeField()
temp = models.FloatField(null = False)
temp_min = models.FloatField(null = False)
temp_max = models.FloatField(null = False)
pressure = models.FloatField(null = False)
sea_level = models.FloatField(null = False)
grnd_level = models.FloatField(null = False)
humidity = models.FloatField(null = False)
main = models.CharField(max_length=200)
description = models.CharField(max_length=30)
clouds = models.IntegerField(null=False)
wind_speed = models.FloatField(null = False)
wind_degree = models.FloatField(null = False)
if I try executing 'python manage.py theweather'(the weather being the name of management command file), am getting an error stating:
nantapur
invalid literal for int() with base 10: 'Anantapur'
Chittoor
invalid literal for int() with base 10: 'Chittoor'
Kakinada
invalid literal for int() with base 10: 'Kakinada'
for all the city names in headquarters.csv file.
what is the solution for this error?
You should use named parameters, using positional ones is "unstable" since if you later add some field, then it might go wrong. Note that the first parameter is here the implicit primary key:
wd = weatherdata.objects.create(
city_name=city_name,
city_id=city_id,
latitude=latitude,
longitude=longitude,
dt_txt=dt_txt,
temp=temp,
temp_min=temp_min,
temp_max=temp_max,
pressure=pressure,
sea_level=sea_level,
grnd_level=grnd_level,
humidity=humidity,
main=main,
description=description,
clouds=clouds,
wind_speed=wind_speed,
wind_deg=wind_deg
)
That being said, I'm not sure the modeling is good here, it contains a lot of data duplication.
Note that class names are usually written in CamelCase, so it should be WeatherData, not weatherdata.

Categories