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.3 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.forms.util import ErrorList
#models
from models import City
from country.models import Country
from directories.models import Iata
#functions
from functions.translate import fill_with_signal
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())
#
city_id = 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=False, max_length=255,
widget=forms.TextInput(attrs={'style':'width: 550px'}))
self.fields['keywords_%s' % code] = forms.CharField(label='Дескрипшен', required=False, max_length=255,
widget=forms.TextInput(attrs={'style':'width: 550px'}))
self.fields['descriptions_%s' % code] = forms.CharField(label='Кейвордс', required=False, max_length=255,
widget=forms.TextInput(attrs={'style':'width: 550px'}))
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 id:
city = City.objects.get(id=id)
else:
city = City()
city.phone_code = data.get('phone_code')
city.population = data.get('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
# url generate for city: "country_name-city_name"
city.url = '%s-'%translit_with_separator(city.country.name) + translit_with_separator(data['name_ru']).lower()
# fill translated fields and save object
fill_with_signal(City, city, data)
# save files
check_tmp_files(city, data['key'])
def clean(self):
id = self.cleaned_data.get('city_id')
name_ru = self.cleaned_data.get('name_ru')
country = self.cleaned_data.get('country')
city = City.objects.filter(
url='%s-%s'%(translit_with_separator(country.name), translit_with_separator(name_ru))
)
if city and str(city[0].id) != id:
msg = 'Город с таким названием уже существует'
self._errors['name_ru'] = ErrorList([msg])
del self.cleaned_data['name_ru']
return self.cleaned_data
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)
class CityDeleteForm(forms.ModelForm):
url = forms.CharField(widget=forms.HiddenInput())
class Meta:
model = City
fields = ('url',)