From 4690d4e19c30a9c5e02bfd6c0ebda30805229322 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9D=D0=B0=D0=B7=D0=B0=D1=80=20=D0=9A=D0=BE=D1=82=D1=8E?= =?UTF-8?q?=D0=BA?= Date: Wed, 11 Feb 2015 17:41:29 +0200 Subject: [PATCH] Import work --- .../management/commands/exposition_load.py | 3 +- file/forms.py | 4 +- import_xls/excel_settings.py | 12 +- import_xls/utils.py | 6 +- place_exposition/admin_urls.py | 2 +- place_exposition/forms.py | 15 +- .../commands/place_exposition_load.py | 156 +++++++++--------- place_exposition/models.py | 41 ++++- place_exposition/views.py | 2 +- .../place_exposition/place_exposition.html | 6 +- 10 files changed, 150 insertions(+), 97 deletions(-) diff --git a/exposition/management/commands/exposition_load.py b/exposition/management/commands/exposition_load.py index 2e3a9b2a..7a755020 100644 --- a/exposition/management/commands/exposition_load.py +++ b/exposition/management/commands/exposition_load.py @@ -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] diff --git a/file/forms.py b/file/forms.py index 8816ec37..094e6e7e 100644 --- a/file/forms.py +++ b/file/forms.py @@ -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): """ diff --git a/import_xls/excel_settings.py b/import_xls/excel_settings.py index 0473b787..fb9510b5 100644 --- a/import_xls/excel_settings.py +++ b/import_xls/excel_settings.py @@ -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'}, diff --git a/import_xls/utils.py b/import_xls/utils.py index 807202c8..b2c29481 100644 --- a/import_xls/utils.py +++ b/import_xls/utils.py @@ -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 diff --git a/place_exposition/admin_urls.py b/place_exposition/admin_urls.py index 47ab735d..6de2ec5c 100644 --- a/place_exposition/admin_urls.py +++ b/place_exposition/admin_urls.py @@ -10,7 +10,7 @@ urlpatterns = patterns('place_exposition.admin', url(r'^all/$', PlaceExpositionListView.as_view()), #url(r'^add.*/$', 'exposition_add'), - #url(r'^delete/(?P.*)/$', 'exposition_delete'), + url(r'^delete/(?P.*)/$', 'exposition_delete'), #url(r'^change/(?P.*)/$', 'exposition_change'), #url(r'^copy/(?P.*)/$', 'place_exposition_copy'), url(r'^(?P.*)/$', PlaceExpositionView.as_view()), diff --git a/place_exposition/forms.py b/place_exposition/forms.py index d8a4a818..0aac6a59 100644 --- a/place_exposition/forms.py +++ b/place_exposition/forms.py @@ -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 diff --git a/place_exposition/management/commands/place_exposition_load.py b/place_exposition/management/commands/place_exposition_load.py index c2f889e8..c1b5435a 100644 --- a/place_exposition/management/commands/place_exposition_load.py +++ b/place_exposition/management/commands/place_exposition_load.py @@ -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 \ No newline at end of file diff --git a/place_exposition/models.py b/place_exposition/models.py index 5d90d64b..96dda2c7 100644 --- a/place_exposition/models.py +++ b/place_exposition/models.py @@ -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) \ No newline at end of file +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) +""" \ No newline at end of file diff --git a/place_exposition/views.py b/place_exposition/views.py index aac4d1dc..13ceea97 100644 --- a/place_exposition/views.py +++ b/place_exposition/views.py @@ -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) diff --git a/templates/admin/place_exposition/place_exposition.html b/templates/admin/place_exposition/place_exposition.html index 761c9642..add84f46 100644 --- a/templates/admin/place_exposition/place_exposition.html +++ b/templates/admin/place_exposition/place_exposition.html @@ -192,7 +192,7 @@
-

Павилионы

+

Павильоны

{% if object %} @@ -200,7 +200,7 @@ - + @@ -358,7 +358,7 @@
-

Мета даные

+

Мета данные

Название павилионаНазвание павильона Номер Вместимость