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.
145 lines
6.6 KiB
145 lines
6.6 KiB
# -*- coding: utf-8 -*-
|
|
from django import forms
|
|
from django.conf import settings
|
|
from ckeditor.widgets import CKEditorWidget
|
|
from django.core.exceptions import ValidationError
|
|
#models
|
|
from models import City
|
|
from country.models import Country
|
|
from directories.models import Iata
|
|
#functions
|
|
from functions.translate import fill_trans_fields_all, populate_all
|
|
from functions.form_check import is_positive_integer, translit_with_separator
|
|
from functions.files import check_tmp_files
|
|
|
|
|
|
class CityForm(forms.Form):
|
|
"""
|
|
Create City form
|
|
|
|
In __init__ function creates dynamical fields
|
|
|
|
save function saves data in City object. If it doesnt exist create new object
|
|
"""
|
|
|
|
country = forms.ModelChoiceField(label='Страна', queryset=Country.objects.all(), empty_label=None)
|
|
population = forms.CharField(label='Население', required=False,
|
|
widget=forms.TextInput(attrs={'placeholder':'Население'}))
|
|
phone_code = forms.CharField(label='Код города', required=False,
|
|
widget=forms.TextInput(attrs={'placeholder':'Код города'}))
|
|
code_IATA = forms.ModelChoiceField(label='Код IATA', queryset=Iata.objects.all(), empty_label=None, required=False)
|
|
country = forms.ModelChoiceField(label='Страна', queryset=Country.objects.all(), empty_label=None)
|
|
#field for comparing tmp files
|
|
key = forms.CharField(required=False, widget=forms.HiddenInput())
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
"""
|
|
create dynamical translated fields fields
|
|
and fills select fields
|
|
"""
|
|
super(CityForm, self).__init__(*args, **kwargs)
|
|
#creates translated forms 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):
|
|
# uses 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)
|
|
self.fields['description_%s' % code] = forms.CharField(label='Описание',
|
|
required=False, widget=CKEditorWidget)
|
|
self.fields['famous_places_%s' % code] = forms.CharField(label='Знаменитые места',
|
|
required=False, widget=CKEditorWidget())
|
|
self.fields['shoping_%s' % code] = forms.CharField(label='Шопинг', required=False, widget=CKEditorWidget())
|
|
self.fields['transport_%s' % code] = forms.CharField(label='Транспорт', required=False, widget=CKEditorWidget())
|
|
#meta data
|
|
self.fields['title_%s' % code] = forms.CharField(label='Тайтл', required=required, max_length=255,
|
|
widget=forms.TextInput(attrs={'style':'width: 550px'}))
|
|
self.fields['keywords_%s' % code] = forms.CharField(label='Дескрипшен', required=required, max_length=255,
|
|
widget=forms.TextInput(attrs={'style':'width: 550px'}))
|
|
self.fields['descriptions_%s' % code] = forms.CharField(label='Кейвордс', required=required, max_length=255,
|
|
widget=forms.TextInput(attrs={'style':'width: 550px'}))
|
|
|
|
#creates select inputs ind fill it
|
|
#countries = ((item.id, item.name) for item in Country.objects.all())
|
|
#self.fields['country'] = forms.ChoiceField(label='Страна', choices=countries, required=False)
|
|
|
|
|
|
def save(self, id=None):
|
|
"""
|
|
change City object with id = id
|
|
N/A add new City object
|
|
usage: form.save(obj) - if change city
|
|
form.save() - if add city
|
|
"""
|
|
data = self.cleaned_data
|
|
#create new City object or get exists
|
|
if not id:
|
|
city = City()
|
|
else:
|
|
city = City.objects.get(id=id)
|
|
|
|
city.url = translit_with_separator(data['name_ru'])
|
|
city.phone_code = data['phone_code']
|
|
city.population = data['population']
|
|
if data.get('code_IATA'):
|
|
city.code_IATA = Iata.objects.get(id=data['code_IATA'].id)#.id cause select uses queryset
|
|
if data.get('country'):
|
|
city.country = Country.objects.get(id=data['country'].id)#.id cause select uses queryset
|
|
|
|
# uses because in the next loop data will be overwritten
|
|
city.save()
|
|
|
|
#will be saved populated fields
|
|
zero_fields = {}
|
|
#fills all translated fields with data
|
|
#if saves new object, will fill city object. otherwise existing object of City model
|
|
fill_trans_fields_all(City, city, data, id, zero_fields)
|
|
|
|
#autopopulate
|
|
#populate empty fields and fields which was already populated
|
|
city_id = getattr(city, 'id')
|
|
populate_all(City, data, city_id, zero_fields)
|
|
#save files
|
|
check_tmp_files(city, data['key'])
|
|
|
|
def clean_name_ru(self):
|
|
"""
|
|
check name which must be unique because it generate slug field
|
|
"""
|
|
cleaned_data = super(CityForm, self).clean()
|
|
name_ru = cleaned_data.get('name_ru')
|
|
try:
|
|
city = City.objects.get(url=translit_with_separator(name_ru))
|
|
if(city.url == translit_with_separator(name_ru)):
|
|
return name_ru
|
|
except:
|
|
return name_ru
|
|
|
|
raise ValidationError('Город с таким названием уже существует')
|
|
|
|
|
|
def clean_phone_code(self):
|
|
"""
|
|
checking phone_code
|
|
"""
|
|
cleaned_data = super(CityForm, self).clean()
|
|
phone_code = cleaned_data.get('phone_code')
|
|
if not phone_code:
|
|
return
|
|
|
|
deduct = ('-','(',')','.',' ')
|
|
for elem in deduct:
|
|
phone_code = phone_code.replace(elem, '')
|
|
if phone_code.isdigit():
|
|
return phone_code
|
|
else:
|
|
raise ValidationError('Введите правильный телефонный код')
|
|
|
|
def clean_population(self):
|
|
"""
|
|
checking population
|
|
"""
|
|
cleaned_data = super(CityForm, self).clean()
|
|
population = cleaned_data.get('population').strip()
|
|
return is_positive_integer(population) |