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.
 
 
 
 
 
 

233 lines
6.3 KiB

# -*- coding: utf-8 -*-
import urllib2
import time, xlrd
import os
from PIL import Image
from django.conf import settings
from django.utils import translation
from hvad.utils import get_translation_aware_manager
from place_exposition.models import PlaceExposition
from events.models import TargetAudience
from country.models import Country
from city.models import City
from theme.models import Theme, Tag
from functions.files import get_alternative_filename
from accounts.models import User
from django.utils.translation import ugettext as _
def to_int(val):
"""
Reverse function to get_int
return None if value isnt integer
"""
try:
return int(val)
except ValueError:
return None
def to_date(value):
if not value:
return None
if isinstance(value, unicode) or isinstance(value, str):
try:
t = time.strptime(value, "%d.%m.%Y")
except ValueError:
try:
t = time.strptime(value, "%d/%m/%Y")
except ValueError:
return None
if isinstance(value, float):
t = xlrd.xldate_as_tuple(value, 0)+(0,0,0)
return time.strftime("%Y-%m-%d", t)
def to_datetime(value):
if not value:
return None
if isinstance(value, unicode) or isinstance(value, str):
t = time.strptime(value, "%Y-%m-%d %H:%M:%S")
return time.strftime("%Y-%m-%d %H:%M:%S", t)
def to_country(value):
try:
query = get_translation_aware_manager(Country)
country = query.filter(name=value)[0]
return country
except IndexError:
print('---------------------')
print(value.encode('utf8'))
print('AAAAAAAA')
return None
def to_city(value, lang, country):
try:
# get city by name
#objects = get_translation_aware_manager(City)
# except IndexError if no found
city = City.objects.filter(translations__name=value, country=country)[0]
# print(city)
return city.id
except IndexError:
print('---------city error------------')
print(value.encode('utf8'))
print('---------------------')
return None
def to_theme(obj, value):
if isinstance(value, float) or isinstance(value, int):
if (value - int(value) > 0):
value = str(value)
else:
value = str(int(value))
theme_ids = value.split('.')
else:
theme_ids = value.split(',')
if theme_ids == ['']:
return _(u'Неправильное значение')
obj.theme.clear()
obj.theme.add(*Theme.objects.filter(id__in=theme_ids))
if not Theme.objects.filter(id__in=theme_ids).exists():
return _(u'Нет совпадений')
return None
def to_tag(obj,value):
if value == [""]:
return None
names = value.split(',')
translation.activate('en')
if names:
obj.tag.clear()
obj.tag.add(*Tag.objects.filter(translations__name__in=names, theme__in=obj.theme.all()))
return None
def to_place(value):
value = value.replace('/', '')
try:
place = PlaceExposition.objects.get(url=value)
return place
except PlaceExposition.DoesNotExist:
try:
place = PlaceExposition.objects.get(id=value)
return place
except:
return None
def to_periodic(value):
periodic = {'': 0, u'Ежегодно': 1.0, u'2 раза в год': 2.0, u'3 раза в год': 3.0,
u'4 раза в год': 4.0, u'5 раз в год': 5.0, u'Раз в 2 года': 0.5,
u'Раз в 3 года': 0.33, u'Раз в 4 года': 0.25}
return periodic.get(value, 0)
def to_audience(obj, value):
# new_list = []
# if value:
# translation.activate('ru')
# l = value.split(', ')
# target_audience = TargetAudience.objects.all()
# print l
# for value in l:
# for ta in target_audience:
# if value == ta.title:
# new_list.append(ta.pk)
# return new_list
translation.activate('ru')
target_audience = TargetAudience.objects.filter(title__in=value.split(', ')).values_list('pk', flat=True)
obj.audience.clear()
obj.audience.add(*TargetAudience.objects.filter(id__in=target_audience))
return None
def get_audience(value):
new_list = [x.title for x in value.all()]
return ', '.join(new_list)
import types
def save_logo(obj, path):
if not path:
return None
file_name = path.split('/')[-1]
logo_path = obj.logo.field.upload_to
if isinstance(logo_path, types.FunctionType):
logo_path = logo_path(obj, obj.url)
logo_path = '/'.join(logo_path.split('/')[:-1])
full_path = settings.MEDIA_ROOT + logo_path
try:
alt_name = get_alternative_filename(full_path, file_name)
except UnicodeEncodeError:
return _(u'Некоректное название файла')
download_to = full_path+alt_name
if path.startswith('http://') or path.startswith('https://'):
url = path
elif path.startswith('/'):
url = 'http://expomap.ru' + path
elif path.startswith('images'):
url = 'http://expomap.ru/' + path
else:
return None
try:
response = urllib2.urlopen(url, timeout=5)
except:
return _(u'Превышено время ожидания')
with open(download_to,'wb') as f:
try:
f.write(response.read())
f.close()
except:
# can be timeout
return _(u'Превышено время ожидания')
try:
# check if image
im=Image.open(download_to)
except IOError:
os.remove(download_to)
return _(u'Неправильный формат логотипа')
obj.logo = logo_path + alt_name
try:
obj.save()
except:
print('logo exception. logo: %s'%obj.logo)
return _(u'Неизвестная ошибка')
def check_quality_label(obj, value, label):
bit = obj.quality_label
try:
value = int(value)
except:
return bit
if value:
setattr(bit, label, True)
return bit
def to_user(value):
try:
return User.objects.get(id=value)
except User.DoesNotExist:
return User.objects.get(id=1)