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.
 
 
 
 
 
 

310 lines
14 KiB

# -*- coding: utf-8 -*-
from django import forms
from django.conf import settings
from ckeditor.widgets import CKEditorWidget
from django.core.exceptions import ValidationError
from django.core.validators import validate_email, URLValidator
from django.forms.util import ErrorList
#models
from models import PlaceExposition, EXPOSITION_TYPE, Hall
from country.models import Country
from city.models import City
#functions
from functions.translate import fill_with_signal
from functions.files import check_tmp_files
from functions.form_check import is_positive_integer, translit_with_separator
from functions.custom_fields import LocationWidget
from functions.admin_forms import AdminFilterForm
from django.utils.translation import ugettext as _
class ExpositionForm(forms.Form):
"""
Create Exposition form for creating place_exposition
__init__ uses for dynamic creates fields
save function saves data in PlaceExposition object. If it doesnt exist create new object
"""
types = [(item1, item2) for item1, item2 in EXPOSITION_TYPE]
type = forms.ChoiceField(required=False, choices=types)
logo = forms.ImageField(label=_(u'Logo'), required=False, max_length=500)
country = forms.ChoiceField(label=_(u'Страна'), 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=_(u'Город'), widget=forms.HiddenInput())
address = forms.CharField(label=_(u'Адрес'), widget=LocationWidget, required=False)
phone = forms.CharField(label=_(u'Телефон'), required=False,
widget=forms.TextInput(attrs={'placeholder': _(u'Введите телефон')}))
fax = forms.CharField(label=_(u'Факс'), required=False,
widget=forms.TextInput(attrs={'placeholder': _(u'Введите факс')}))
web_page = forms.URLField(label=_(u'Веб-сайт'), required=False,
widget=forms.TextInput(attrs={'placeholder': _(u'Введите адрес сайта')}))#
email = forms.EmailField(label=_(u'Email'), required=False,
widget=forms.TextInput(attrs={'placeholder': _(u'Введите email')}))#
#
foundation_year = forms.CharField(label=_(u'Год основания'), required=False,
widget=forms.TextInput(attrs={'placeholder': _(u'Год основания')}))
total_area = forms.CharField(label='Общая выставочная площадь', required=False,
widget=forms.TextInput(attrs={'placeholder': _(u'Общая выст. площадь')}))
closed_area = forms.CharField(label=_(u'Закрытая выставочная площадь'), required=False,
widget=forms.TextInput(attrs={'placeholder': _(u'Закр. выст. площадь')}))
open_area = forms.CharField(label=_(u'Открытая выставочная площадь'), required=False,
widget=forms.TextInput(attrs={'placeholder': _(u'Откр. выст. площадь')}))
total_pavilions = forms.CharField(label=_(u'Количество павильонов'), required=False,
widget=forms.TextInput(attrs={'placeholder': _(u'Количество павильонов')}))
total_halls = forms.CharField(label=_(u'Количество конференц залов'), required=False,
widget=forms.TextInput(attrs={'placeholder': _(u'Конференц залы')}))
#
wifi = forms.BooleanField(label='Wi-fi', required=False)
bank = forms.BooleanField(label=_(u'Банк/Банкоматы'), required=False)
children_room = forms.BooleanField(label=_(u'Детская комната'), required=False)
disabled_service = forms.BooleanField(label=_(u'Сервис для инвалидов'), required=False)
conference_centre = forms.BooleanField(label=_(u'Конгресс-центр'), required=False)
business_centre = forms.BooleanField(label=_(u'Бизнес-центр'), required=False)
online_registration = forms.BooleanField(label=_(u'Онлайн регистрация'), required=False)
cafe = forms.BooleanField(label=_(u'Кафе'), required=False)
terminals = forms.BooleanField(label=_(u'Информационные терминалы'), required=False)
parking = forms.BooleanField(label=_(u'Парковка'), required=False)
press_centre = forms.BooleanField(label=_(u'Пресс-центр'), required=False)
mobile_application = forms.BooleanField(label=_(u'Мобильное приложение'), required=False)
def __init__(self, *args, **kwargs):
"""
create dynamical translated fields fields
"""
super(ExpositionForm, self).__init__(*args, **kwargs)
# creates translated form fields, example: name_ru, name_en
# len(10) is a hack for detect if settings.LANGUAGES is not configured it return all langs
if len(settings.LANGUAGES) in range(10):
for lid, (code, name) in enumerate(settings.LANGUAGES):
# using enumerate for detect iteration number
# first iteration is a default lang so it required fields
required = True if lid == 0 else False
self.fields['name_%s' % code] = forms.CharField(label=_(u'Название'), required=required)
self.fields['main_title_%s' % code] = forms.CharField(label=_(u'Краткое описание'), required=False, widget=CKEditorWidget)#5
self.fields['description_%s' % code] = forms.CharField(label=_(u'Полное описание'), required=False, widget=CKEditorWidget)
self.fields['adress_%s' % code] = forms.CharField(label=_(u'Дополнительная инф по адресу'), required=False, max_length=255,
widget=forms.TextInput(attrs={'style':'width: 550px'}))
#
self.fields['total_year_action_%s' % code] = forms.CharField(label=_(u'Количество мероприятий в год'), required=False, widget=CKEditorWidget)
#meta data
self.fields['title_%s' % code] = forms.CharField(label=_(u'Тайтл'), required=False, max_length=255,
widget=forms.TextInput(attrs={'style':'width: 550px'}))
self.fields['keywords_%s' % code] = forms.CharField(label=_(u'Дескрипшен'), required=False, max_length=255,
widget=forms.TextInput(attrs={'style':'width: 550px'}))
self.fields['descriptions_%s' % code] = forms.CharField(label=_(u'Кейвордс'), required=False, max_length=255,
widget=forms.TextInput(attrs={'style':'width: 550px'}))
def save(self, obj=None):
"""
change PlaceExposition model object with id = id
N/A add new PlaceExposition model object
usage: form.save(obj) - if change place_exposition
form.save() - if add place_exposition
"""
data = self.cleaned_data
if not obj:
place_exposition = PlaceExposition()
else:
place_exposition = obj
if not getattr(place_exposition, 'url'):
if data.get('name_en'):
place_exposition.url = translit_with_separator(data['name_en'].strip()).lower()
else:
place_exposition.url = translit_with_separator(data['name_ru'].strip()).lower()
if data.get('logo'):
place_exposition.logo = data['logo']
place_exposition.type = data['type']
place_exposition.address = data['address']
place_exposition.phone = data['phone']
place_exposition.fax = data['fax']
place_exposition.web_page = data['web_page']
place_exposition.email = data['email']
place_exposition.foundation_year = data['foundation_year']
place_exposition.total_area = data['total_area']
place_exposition.closed_area = data['closed_area']
place_exposition.open_area = data['open_area']
place_exposition.total_pavilions = data['total_pavilions']
place_exposition.total_halls = data['total_halls']
place_exposition.wifi = data['wifi']
place_exposition.bank = data['bank']
place_exposition.children_room = data['children_room']
place_exposition.disabled_service = data['disabled_service']
place_exposition.conference_centre = data['conference_centre']
place_exposition.business_centre = data['business_centre']
place_exposition.online_registration = data['online_registration']
place_exposition.cafe = data['cafe']
place_exposition.terminals = data['terminals']
place_exposition.parking = data['parking']
place_exposition.press_centre = data['press_centre']
place_exposition.mobile_application = data['mobile_application']
if data.get('country'):
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)
place_exposition.save()
return place_exposition
def clean_phone(self):
"""
phone checking
"""
cleaned_data = super(ExpositionForm, self).clean()
phone = cleaned_data.get('phone')
if not phone:
return
deduct = ('-','(',')','.','+',' ')
for elem in deduct:
phone = phone.replace(elem, '')
if phone.isdigit():
return phone
else:
raise ValidationError(_(u'Введите правильный телефон'))
def clean_fax(self):
"""
fax checking
"""
cleaned_data = super(ExpositionForm, self).clean()
fax = cleaned_data.get('fax')
if not fax:
return
deduct = ('-','(',')','.',' ', '+')
for elem in deduct:
fax = fax.replace(elem, '')
if fax.isdigit():
return fax
else:
raise ValidationError(_(u'Введите правильный факс'))
def clean_foundation_year(self):
"""
checking foundation_year
"""
cleaned_data = super(ExpositionForm, self).clean()
foundation_year = cleaned_data.get('foundation_year').strip()
return is_positive_integer(foundation_year)
def clean_total_area(self):
"""
checking foundation_year
"""
cleaned_data = super(ExpositionForm, self).clean()
total_area = cleaned_data.get('total_area').strip()
return is_positive_integer(total_area)
def clean_closed_area(self):
"""
checking closed_area
"""
cleaned_data = super(ExpositionForm, self).clean()
closed_area = cleaned_data.get('closed_area').strip()
return is_positive_integer(closed_area)
def clean_open_area(self):
"""
checking open_area
"""
cleaned_data = super(ExpositionForm, self).clean()
open_area = cleaned_data.get('open_area').strip()
return is_positive_integer(open_area)
def clean_total_pavilions(self):
"""
checking total_pavilions
"""
cleaned_data = super(ExpositionForm, self).clean()
total_pavilions = cleaned_data.get('total_pavilions').strip()
return is_positive_integer(total_pavilions)
def clean_total_halls(self):
"""
checking total_halls
"""
cleaned_data = super(ExpositionForm, self).clean()
total_halls = cleaned_data.get('total_halls').strip()
return is_positive_integer(total_halls)
class PlaceExpositionFormDelete(forms.ModelForm):
url = forms.CharField(widget=forms.HiddenInput())
class Meta:
model = PlaceExposition
fields = ('url',)
class HallForm(forms.Form):
url = '/admin/place_exposition/add-hall/'
number = forms.CharField(widget=forms.TextInput(attrs={'style': 'width:30px'}),required=False,
label=_(u'Номер'))
capacity = forms.CharField(widget=forms.TextInput(attrs={'style': 'width:60px'}), required=False,
label=_(u'Вместимость'))
def __init__(self, *args, **kwargs):
"""
create dynamical translated fields fields
"""
super(HallForm, self).__init__(*args, **kwargs)
# creates translated form fields, example: name_ru, name_en
# len(10) is a hack for detect if settings.LANGUAGES is not configured it return all langs
if len(settings.LANGUAGES) in range(10):
for lid, (code, name) in enumerate(settings.LANGUAGES):
# using enumerate for detect iteration number
# first iteration is a default lang so it required fields
required = True if lid == 0 else False
self.fields['name_%s' % code] = forms.CharField(label='Название', required=required)
def clean_capacity(self):
cleaned_data = super(HallForm, self).clean()
capacity = cleaned_data.get('capacity').strip()
return is_positive_integer(capacity, _(u'Вместимость должна состоять из цифр'))
def save(self, place_exposition, id=None):
if id:
hall = Hall.objects.get(id=id)
else:
hall = Hall()
data = self.cleaned_data
hall.capacity = data['capacity']
hall.number = data['number']
hall.place_exposition = place_exposition
fill_with_signal(Hall, hall, data)
hall.save()
return hall
class PlaceExpositionFilter(AdminFilterForm):
country = forms.MultipleChoiceField(choices=[(item.id, item.name) for item in list(Country.objects.all())],
required=False, widget=forms.SelectMultiple())
model = PlaceExposition
def filter(self):
qs = super(PlaceExpositionFilter, self).filter()
data = self.cleaned_data
country = data['country']
if country:
qs = qs.filter(country_id__in=country)
return qs