# -*- 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 from django.utils.translation import get_language as lang #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 from functions.admin_forms import AdminFilterForm from django.utils.translation import ugettext_lazy as _ 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=_(u'Страна'), queryset=Country.objects.filter(translations__language_code=lang()).order_by('translations__name'), empty_label=None) population = forms.CharField(label=_(u'Население'), required=False, widget=forms.TextInput(attrs={'placeholder':_(u'Население')})) phone_code = forms.CharField(label=_(u'Код города'), required=False, widget=forms.TextInput(attrs={'placeholder':_(u'Код города')})) code_IATA = forms.ModelChoiceField(label=_(u'Код IATA'), queryset=Iata.objects.all(), empty_label=None, required=False) inflect = forms.CharField(label=_(u'Inflect'), required=False) logo = forms.ImageField(label=_(u'Logo'), required=False) #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=_(u'Название'), required=required) self.fields['region_%s' % code] = forms.CharField(label=_(u'Регион'), required=False) self.fields['description_%s' % code] = forms.CharField(label=_(u'Описание'), required=False, widget=CKEditorWidget) self.fields['famous_places_%s' % code] = forms.CharField(label=_(u'Знаменитые места'), required=False, widget=CKEditorWidget()) self.fields['shoping_%s' % code] = forms.CharField(label=_(u'Шопинг'), required=False, widget=CKEditorWidget()) self.fields['transport_%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, 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() if not getattr(city, 'url'): city.url = translit_with_separator(data['name_ru'].strip()).lower() city.phone_code = data['phone_code'] city.population = data.get('population') city.inflect = data['inflect'] if data.get('logo'): city.logo = data['logo'] else: city.logo = '' 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 = data['country']# .id cause select uses queryset #city.country = Country.objects.get(id=data['country'].id)# .id cause select uses queryset # fill translated fields and save object fill_with_signal(City, city, data) city.save() # 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') name_en = self.cleaned_data.get('name_en') country = self.cleaned_data.get('country') """ city = City.objects.filter( url='%s-%s'%(translit_with_separator(country.name), translit_with_separator(name_en)) ) if not city: 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(_(u'Введите правильный телефонный код')) 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',) class CityFilterForm(AdminFilterForm): country = forms.ChoiceField(choices=[('', '')]+[(item.id, item.name) for item in Country.objects.language().all()], required=False, label=_(u'Страна')) model = City def filter(self): qs = super(CityFilterForm, self).filter() data = self.cleaned_data country_id = data['country'] if country_id: qs = qs.filter(country__id=country_id) return qs