Задача :
скопировать сайт на django1.3, подвязать разные домены.
Сделано :
Скопировал папку с проектом, скопировал бд, развернул отдельно виртуальное окружение, повесил на uwsgi и nginx. все работает.
Проблема :
В админке есть функционал - импорт прайса. Загружается xls файл и с него подтягиваются в базу цены. Но если я загружаю прайс в domain1 , то цены обновляются и на domain2. И наоборот. БД подключены разные, если править товары в админке , то обновляется только на котором правил..
Код контроллера:
def import_1c_price(request):
if request.method == 'POST':
form = Import1CPriceForm(request.POST, request.FILES)
if form.is_valid():
warehouse = form.cleaned_data['warehouse']
row_number = form.cleaned_data['row_number']
notification_email = form.cleaned_data['notification_email']
notification_email = notification_email.replace(' ', '')
notification_email = notification_email.split(',')
data = request.FILES['price_file']
path = default_storage.save('tmp/1c_price.{}'.format(form.cleaned_data['price_file'].name.split('.')[-1]),
ContentFile(data.read()))
tmp_file = os.path.join(settings.MEDIA_ROOT, path)
from .tasks import load_1c_items_to_database
load_1c_items_to_database.apply_async(
args=[
tmp_file,
row_number,
warehouse,
request.user,
notification_email
],
countdown=1,
expires=2
)
return HttpResponseRedirect(reverse('admin:import_1c_price'))
else:
form = Import1CPriceForm()
result = {
'title': u'Импорт прайса',
'opts': Item._meta,
'form': form
}
return render_to_response('admin/catalog/import_price.html', result, context_instance=RequestContext(request))
Код функции load_1c_items_to_database:
def load_1c_items_to_database(tmp_file, row_number, warehouse, user, notification_email):
exclude_list = []
start_time = datetime.now()
result = {
'action': 'notification',
'user': user.email,
'title': u'Импорт прайса',
'message': u'Файл загружен и уже обрабатывается.',
'icon': '/static/images/notification_info.png'
}
socket_notification.apply_async(
args=[result],
countdown=3,
expires=4
)
rb = xlrd.open_workbook(tmp_file)
sheet = rb.sheet_by_index(0)
updated = 0
article = 4
name = 0
if warehouse.uid == 'kiev_uid':
count = 8
wholesale_price = 7
big_wholesale_price = 6
wholesale_price_2 = 5
else:
count = 7
wholesale_price = 6
big_wholesale_price = 5
wholesale_price_2 = None
errors = ''
not_found_items = []
for rownum in range(row_number, sheet.nrows):
try:
row = sheet.row_values(rownum)
if len(row) < 8:
continue
try:
article_val = u'%s' % decimal.Decimal(row[article])
except:
article_val = u'%s' % row[article]
if article_val and row[name]:
item = Item.objects.filter(article=article_val, warehouse=warehouse)
if item:
item = item[0]
item.count = row[count]
item.wholesale_price = row[wholesale_price] if row[wholesale_price] else 0
item.big_wholesale_price = row[big_wholesale_price] if row[big_wholesale_price] else 0
if wholesale_price_2:
item.wholesale_price_2 = row[wholesale_price_2] if row[wholesale_price_2] else 0
try:
item.name = row[name].strip()[:128]
except Exception as e:
item.name = str(row[name])
item.save()
updated += 1
exclude_list.append(item.id)
else:
not_found_items.append([article_val, row[name]])
except Exception, e:
continue
Item.objects.filter(warehouse=warehouse).exclude(id__in=exclude_list).update(
wholesale_price=0,
wholesale_price_2=0,
wholesale_price_3=0,
wholesale_price_4=0,
big_wholesale_price=0
)
shutil.rmtree(os.path.join(settings.MEDIA_ROOT, 'tmp'))
updated_text = u''
if updated:
updated_text = u'\nТоваров обновлено {}шт.'.format(updated)
messages_text = u"Импорт данных успешно завершен!{}".format(updated_text)
result = {
'action': 'notification',
'user': user.email,
'title': u'Импорт прайса',
'message': messages_text,
'icon': '/static/images/notification_success.png'
}
socket_notification.apply_async(
args=[result],
countdown=3,
expires=4
)
end_time = datetime.now()
service_mail = settings.DEFAULT_FROM_EMAIL
from_email = u'%s <%s>' % ('MobiMag', service_mail, )
txt_content = render_to_string('catalog/emails_admin/import_results.txt', {
'messages_text': messages_text,
'not_found_items': not_found_items,
'warehouse': warehouse,
'end_time': end_time,
'start_time': start_time
})
html_content = render_to_string('catalog/emails_admin/import_results.html', {
'messages_text': messages_text,
'not_found_items': not_found_items,
'warehouse': warehouse,
'end_time': end_time,
'start_time': start_time
})
msg = EmailMultiAlternatives(
subject=u'Результаты импорта для склада {}'.format(warehouse.name),
body=txt_content,
from_email=from_email,
to=notification_email
)
msg.attach_alternative(html_content, 'text/html')
msg.send(fail_silently=True)
return