Import work

remotes/origin/1203
Назар Котюк 11 years ago
parent 5b063224a9
commit 4690d4e19c
  1. 3
      exposition/management/commands/exposition_load.py
  2. 4
      file/forms.py
  3. 12
      import_xls/excel_settings.py
  4. 6
      import_xls/utils.py
  5. 2
      place_exposition/admin_urls.py
  6. 15
      place_exposition/forms.py
  7. 156
      place_exposition/management/commands/place_exposition_load.py
  8. 41
      place_exposition/models.py
  9. 2
      place_exposition/views.py
  10. 6
      templates/admin/place_exposition/place_exposition.html

@ -26,7 +26,7 @@ class Command(BaseCommand):
row_list = [sheet.row_values(row_number) for row_number in range(sheet.nrows)]
labels = [label for label in row_list[0]]
for row_number, row in enumerate(row_list[344:400]):
for row_number, row in enumerate(row_list[1:]):
#print(row_number)
if row[0] != '':
@ -44,6 +44,7 @@ class Command(BaseCommand):
# if id blank - its a new place
object = Exposition()
object.translate('ru')
methods = []
for col_number, cell in enumerate(row):
label = labels[col_number]

@ -17,8 +17,8 @@ import pytils, re
class FileForm(forms.Form):
file_path = forms.FileField(label='Выберите файл')
model = forms.CharField(required=False, widget=forms.HiddenInput())
purposes = [('scheme teritory','Схема територии'),('preview','Превью')]
purpose = forms.ChoiceField(label='Назаначение', choices=purposes)
purposes = [('scheme teritory','Схема территории'),('preview','Превью')]
purpose = forms.ChoiceField(label='Назначение', choices=purposes)
def __init__(self, *args, **kwargs):
"""

@ -247,7 +247,6 @@ def to_phone(value):
value = value.replace(elem, '')
value = to_int(value)
print(value)
return value
@ -279,9 +278,16 @@ def save_halls(obj, value):
name = l[0].strip()
res.append({'area': area, 'name':name, 'number': number})
Hall.objects.filter(place_exposition=obj).delete()
for hall in res:
h = Hall(place_exposition = obj, name=hall.get('name'), number=hall.get('number'), capacity=hall.get('area'))
h.save()
try:
h.save()
except Exception, e:
print('---------------hall error---------')
print e
print('---------------------------------')
place_exp_sett = {
u'ID':{u'field': u'id', u'func': to_int},
@ -295,7 +301,7 @@ place_exp_sett = {
u'Тел.':{u'field': u'phone', u'func': to_phone},
u'Факс':{u'field': u'fax', u'func': to_phone},
u'Фото':{u'field': u'photo', u'func': save_photo, u'method': True},
u'Лого':{u'field': u'logo', u'func': save_file, u'method': True, u'purpose': 'logo'},
u'Лого':{u'field': u'logo', u'func': save_logo, u'method': True},
u'Веб-сайт':{u'field': u'web_page', u'func': unicode},
u'Email':{u'field': u'email', u'func': unicode},
u'Карта проезда':{u'field': u'map', u'func': save_file, u'method': True, u'purpose': 'map'},

@ -41,7 +41,9 @@ def to_country(value):
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):
@ -51,9 +53,9 @@ def to_city(value, lang, country):
# except IndexError if no found
city = City.objects.filter(translations__name=value, country=country)[0]
# print(city)
return city.id
return city
except IndexError:
print('---------------------')
print('---------city error------------')
print(value.encode('utf8'))
print('---------------------')
return None

@ -10,7 +10,7 @@ urlpatterns = patterns('place_exposition.admin',
url(r'^all/$', PlaceExpositionListView.as_view()),
#url(r'^add.*/$', 'exposition_add'),
#url(r'^delete/(?P<url>.*)/$', 'exposition_delete'),
url(r'^delete/(?P<url>.*)/$', 'exposition_delete'),
#url(r'^change/(?P<url>.*)/$', 'exposition_change'),
#url(r'^copy/(?P<url>.*)/$', 'place_exposition_copy'),
url(r'^(?P<url>.*)/$', PlaceExpositionView.as_view()),

@ -27,13 +27,13 @@ class ExpositionForm(forms.Form):
"""
types = [(item1, item2) for item1, item2 in EXPOSITION_TYPE]
type = forms.ChoiceField(required=False, choices=types)
logo = forms.ImageField(label='Logo', required=False)
logo = forms.ImageField(label='Logo', required=False, max_length=500)
country = forms.ChoiceField(label='Страна', choices=[(c.id, c.name) for c in Country.objects.all()])
# creates select input with empty choices cause it will be filled with ajax
city = forms.CharField(label='Город', widget=forms.HiddenInput())
address = forms.CharField(label='Адресс', widget=LocationWidget, required=False)
address = forms.CharField(label='Адрес', widget=LocationWidget, required=False)
phone = forms.CharField(label='Телефон', required=False,
widget=forms.TextInput(attrs={'placeholder': 'Введите телефон'}))
@ -48,7 +48,7 @@ class ExpositionForm(forms.Form):
widget=forms.TextInput(attrs={'placeholder': 'Год основания'}))
total_area = forms.CharField(label='Общая выставочная площадь', required=False,
widget=forms.TextInput(attrs={'placeholder': 'Общая выст. площадь'}))
closed_area = forms.CharField(label='Закрытая выствочная площадь', required=False,
closed_area = forms.CharField(label='Закрытая выставочная площадь', required=False,
widget=forms.TextInput(attrs={'placeholder': 'Закр. выст. площадь'}))
open_area = forms.CharField(label='Открытая выставочная площадь', required=False,
widget=forms.TextInput(attrs={'placeholder': 'Откр. выст. площадь'}))
@ -62,10 +62,10 @@ class ExpositionForm(forms.Form):
children_room = forms.BooleanField(label='Детская комната', required=False)
disabled_service = forms.BooleanField(label='Сервис для инвалидов', required=False)
conference_centre = forms.BooleanField(label='Конгресс-центр', required=False)
business_centre = forms.BooleanField(label='Бизнес центр', required=False)
business_centre = forms.BooleanField(label='Бизнес-центр', required=False)
online_registration = forms.BooleanField(label='Онлайн регистрация', required=False)
cafe = forms.BooleanField(label='Кафе', required=False)
terminals = forms.BooleanField(label='Информационые терминалы', required=False)
terminals = forms.BooleanField(label='Информационные терминалы', required=False)
parking = forms.BooleanField(label='Парковка', required=False)
press_centre = forms.BooleanField(label='Пресс-центр', required=False)
mobile_application = forms.BooleanField(label='Мобильное приложение', required=False)
@ -148,9 +148,10 @@ class ExpositionForm(forms.Form):
place_exposition.country = Country.objects.get(id=data['country'])
if data.get('city'):
place_exposition.city = City.objects.get(id=data['city'])
fill_with_signal(PlaceExposition, place_exposition, data)
a = place_exposition.logo
place_exposition.save()
fill_with_signal(PlaceExposition, place_exposition, data)
return place_exposition

@ -5,7 +5,7 @@ from place_exposition.models import PlaceExposition
from import_xls.excel_settings import import_settings, place_exp_sett
from django.conf import settings
PLACE_FILE = settings.MEDIA_ROOT+'/import/places.xlsx'
PLACE_FILE = settings.MEDIA_ROOT+'import/places_ru.xls'
class Command(BaseCommand):
def handle(self, *args, **options):
@ -17,90 +17,98 @@ class Command(BaseCommand):
labels = [label for label in row_list[0]]
existing = 0
for row_number, row in enumerate(row_list):
for row_number, row in enumerate(row_list[1:]):
new = 0
# go through all rows in file
if row_number > 0:
# first field is label
if row[0] != '':
# in first column ids
if row[0] != '':
# in first column ids
try:
object = PlaceExposition.objects.language('ru').get(id=int(row[0]))
existing += 1
except ValueError:
object = PlaceExposition()
object.translate('ru')
except PlaceExposition.DoesNotExist:
object = PlaceExposition(id= int(row[0]))
object.translate('ru')
existing += 1
else:
# if id blank - its a new place
object = PlaceExposition
try:
object = PlaceExposition.objects.language('ru').get(id=int(row[0]))
existing += 1
except ValueError:
object = PlaceExposition()
object.translate('ru')
methods = []
for col_number, cell in enumerate(row):
# go through row cells
# field name current cell
label = labels[col_number]
setting = place_exp_sett.get(label)
if setting is None:
continue
new = 1
if setting.get('method'):
if cell != "":
methods.append({'func': setting['func'], 'value': cell, 'purpose': setting.get('purpose')})
continue
except PlaceExposition.DoesNotExist:
object = PlaceExposition(id= int(row[0]))
object.translate('ru')
existing += 1
new = 1
else:
# if id blank - its a new place
object = PlaceExposition
object.translate('ru')
methods = []
for col_number, cell in enumerate(row):
# go through row cells
# field name current cell
label = labels[col_number]
setting = place_exp_sett.get(label)
if setting is None:
continue
field_name = setting['field']
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')
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
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, 'ru', getattr(object, extra_value))
else:
value = func(cell)
#if field_name =='adress':
# setattr(object, 'address', google_address(value))
setattr(object, field_name, value)
# in function we add language(need for relation fields)
# and extra value from object (like for city need country)
value = func(cell, 'ru', getattr(object, extra_value))
#object.save()
print('post save %s'% str(object))
"""
try:
print(object)
#object.save()
except IntegrityError:
continue
#url = object.url + translit_with_separator(object.city.name)
#object.url = url
#object.save()
"""
"""
for method in methods:
func = method['func']
if method.get('purpose'):
try:
func(object, method['value'], method['purpose'])
except:
continue
else:
value = func(cell)
#if field_name =='adress':
# setattr(object, 'address', google_address(value))
if field_name == 'city' and new == 0:
pass
else:
try:
func(object, method['value'])
except:
continue
setattr(object, field_name, value)
except ValueError, e:
print(value, field_name)
"""
print(existing)
object.save()
print('post save %s'% str(object))
"""
try:
print(object)
#object.save()
except IntegrityError:
continue
#url = object.url + translit_with_separator(object.city.name)
#object.url = url
#object.save()
"""
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

@ -78,7 +78,7 @@ class PlaceExposition(TranslatableModel, ExpoMixin):
press_centre = models.NullBooleanField()
mobile_application = models.NullBooleanField()
#
logo = models.ImageField(verbose_name='Logo', upload_to=logo_name, blank=True)
logo = models.ImageField(verbose_name='Logo', upload_to=logo_name, blank=True, max_length=255)
rating = models.IntegerField(default=0)
# delete after profiling
@ -263,7 +263,42 @@ class Hall(TranslatableModel):
def calculate_rating(place):
rating_simple = {'address': 20, 'phone': 5, 'fax': 5, 'email': 5,
'web_page': 5, 'logo': 20, 'event_in_year': 5, 'total_area': 5, 'closed_area': 5,
'total_pavilions': 5, 'description':15, 'foundation_year': 5, 'total_halls': 5, 'virtual_tour': 5 }
rating_methods = {'theme': 10, 'tag': 5, 'photo':5}
# base rating
rating = 100
for key, value in rating_simple.iteritems():
if getattr(place, key):
rating += value
place.rating = rating
# call to prevent recursion
post_save.disconnect(create_place, sender=PlaceExposition)
place.save()
post_save.connect(create_place, sender=PlaceExposition)
def create_place(sender, instance, created, **kwargs):
post_save_handler(sender, instance=instance, **kwargs)
calculate_rating(instance)
#test
pre_save.connect(pre_save_handler, sender=PlaceExposition)
post_save.connect(post_save_handler, sender=PlaceExposition)
post_save.connect(post_save_handler, sender=Hall)
post_save.connect(create_place, sender=PlaceExposition)
post_save.connect(post_save_handler, sender=Hall)
"""
def calculate_rating_for_translations(sender, instance, created, **kwargs):
company = instance.master
post_save.disconnect(calculate_rating_for_translations, sender=Company._meta.translations_model)
calculate_rating(company)
post_save.connect(calculate_rating_for_translations, sender=Company._meta.translations_model)
post_save.connect(create_company, sender=Company)
post_save.connect(calculate_rating_for_translations, sender=Company._meta.translations_model)
"""

@ -128,7 +128,7 @@ class PlaceList(ListView):
def get_queryset(self):
lang = translation.get_language()
qs = super(PlaceList, self).get_queryset().filter(language_code=lang)
qs = super(PlaceList, self).get_queryset().filter(language_code=lang).order_by('-rating')
conf_qs = PlaceConference.objects.language().all()
return list(qs)+list(conf_qs)

@ -192,7 +192,7 @@
<div class="box span8">
<div class="box-header well">
<h2><i class="icon-pencil"></i> Павилионы</h2>
<h2><i class="icon-pencil"></i> Павильоны</h2>
</div>
<div class="box-content">
{% if object %}
@ -200,7 +200,7 @@
<table class="table table-hover" style=" width: 100%;">
<thead>
<tr>
<td>Название павилиона</td>
<td>Название павильона</td>
<td>Номер</td>
<td>Вместимость</td>
<td></td>
@ -358,7 +358,7 @@
<div class="box span8">
<div class="box-header well">
<h2><i class="icon-pencil"></i> Мета даные</h2>
<h2><i class="icon-pencil"></i> Мета данные</h2>
</div>
<div class="box-content">

Loading…
Cancel
Save