You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

111 lines
4.1 KiB

# -*- coding: utf-8 -*-
from django.core.management.base import BaseCommand, CommandError
from city.models import City
from country.models import Country
from exposition.models import Exposition
import xlrd, xlwt
from import_xls.excel_settings import event_sett
from django.conf import settings
from import_xls.import_forms import google_address
class Command(BaseCommand):
def handle(self, *args, **options):
f = open(settings.MEDIA_ROOT+'/import/expositions_ru.xlsx', 'r')
book = xlrd.open_workbook(file_contents=f.read())
sheet = book.sheet_by_index(0)
row_list = [sheet.row_values(row_number) for row_number in range(sheet.nrows)]
labels = [label for label in row_list[0]]
print(len(row_list))
for row_number, row in enumerate(row_list):
# go through all rows in file
if row_number > 0:
# first field is label
if row[0] != '':
# in first column ids
try:
object = Exposition.objects.language('en').get(id=int(row[0]))
except ValueError:
object = Exposition()
object.translate('en')
except Exposition.DoesNotExist:
object = Exposition(id= int(row[0]))
object.translate('en')
else:
# if id blank - its a new place
object = Exposition()
object.translate('en')
methods = []
flag = False
for col_number, cell in enumerate(row):
# go through row cells
# field name current cell
label = labels[col_number]
setting = event_sett.get(label)
if setting is None:
continue
if setting.get('method'):
if cell != "":
methods.append({'func': setting['func'], 'value': cell, 'purpose': setting.get('purpose')})
continue
field_name = setting['field']
func = setting.get('func')
if func is not None:
extra_value = setting.get('extra_values')
if extra_value is not None:
# if setting has extra value then
# it is some field like city, theme, tag
# that has relation and can be created
# in function we add language(need for relation fields)
# and extra value from object (like for city need country)
value = func(cell, 'en', getattr(object, extra_value))
else:
value = func(cell)
#if field_name =='adress':
# setattr(object, 'address', google_address(value))
if field_name=='city' and not value:
print('error city')
flag = True
continue
setattr(object, field_name, value)
object.currency = 'USD'
if not flag:
try:
print('pre save %s'% str(object))
object.save()
except:
print('saving error')
continue
print('post save %s'% str(object))
else:
print('bad city')
for method in methods:
func = method['func']
if method.get('purpose'):
try:
func(object, method['value'], method['purpose'])
except:
continue
else:
try:
func(object, method['value'])
except:
continue