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.
 
 
 
 
 
 

197 lines
8.2 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 Company
from country.models import Country
from theme.models import Theme
from city.models import City
#functions
from functions.translate import populate_all, fill_trans_fields_all
from functions.form_check import is_positive_integer
from functions.files import check_tmp_files
from functions.custom_fields import LocationWidget
class CompanyForm(forms.Form):
"""
Create Company form
In __init__ function creates dynamical fields
save function saves data in Company object. If it doesnt exist create new object
"""
url = forms.CharField(label='URL', widget=forms.TextInput(attrs={'placeholder': 'Введите URL'}))
country = forms.ModelChoiceField(label='Страна', queryset=Country.objects.all(), empty_label=None)
theme = forms.ModelMultipleChoiceField(label='Тематики', queryset=Theme.objects.all())
#creates select input with empty choices cause it will be filled with ajax
city = forms.ChoiceField(label='Город', choices=[('','')])
tag = forms.MultipleChoiceField(label='Теги', required=False)
staff_number = forms.CharField(label='Количество сотрудников', required=False,
widget=forms.TextInput(attrs={'placeholder': 'Количество сотрудников'}))
#uses locationwidget
address = forms.CharField(label='Адрес', required=False, widget=LocationWidget)
phone = forms.CharField(label='Телефон', required=False,
widget=forms.TextInput(attrs={'placeholder': 'Введите телефон'}))
fax = forms.CharField(label='Факс', required=False,
widget=forms.TextInput(attrs={'placeholder': 'Введите факс'}))
web_page = forms.CharField(label='Веб-сайт', required=False,
widget=forms.TextInput(attrs={'placeholder': 'Введите адрес сайта'}))
email = forms.CharField(label='Email', required=False,
widget=forms.TextInput(attrs={'placeholder': 'Введите email'}))
social = forms.CharField(label='Социальные страници', required=False)
foundation = forms.CharField(label='Год основания', required=False,
widget=forms.TextInput(attrs={'placeholder': 'Год основания'}))
#field for comparing tmp files
key = forms.CharField(required=False, widget=forms.HiddenInput())
def __init__(self, *args, **kwargs):
"""
create dynamical translated fields fields
"""
super(CompanyForm, 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['specialization_%s' % code] = forms.CharField(label='Специализация', required=False)
self.fields['address_inf_%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 company object with id = id
N/A add new Company object
usage: form.save(obj) - if change company
form.save() - if add company
"""
data = self.cleaned_data
#create new Company object or get exists
if not id:
company = Company()
else:
company = Company.objects.get(id=id)
company.theme.clear()
company.tag.clear()
#simple fields
company.url = data['url']
company.staff_number = data['staff_number']
company.address = data['address']
company.phone = data['phone']
company.fax = data['fax']
company.web_page = data['web_page']
company.email = data['email']
company.foundation = data['foundation']
company.social = data['social']
if data.get('country'):
company.country = Country.objects.get(id=data['country'].id)
if data.get('city'):
company.city = City.objects.get(id=data['city'])
# uses because in the next loop data will be overwritten
company.save()
#fill manytomany fields
for item in data['theme']:
company.theme.add(item.id)#.id cause select uses queryset
for item in data['tag']:
company.tag.add(item)
# uses because in the next loop data will be overwritten
company.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(Company, company, data, id, zero_fields)
#autopopulate
#populate empty fields and fields which was already populated
company_id = getattr(company, 'id')
populate_all(Company, data, company_id, zero_fields)
#save files
check_tmp_files(company, data['key'])
def clean_foundation(self):
"""
checking foundation
"""
cleaned_data = super(CompanyForm, self).clean()
foundation = cleaned_data.get('foundation').strip()
return is_positive_integer(foundation)
def clean_web_page(self):
cleaned_data = super(CompanyForm, self).clean()
web_page = cleaned_data.get('web_page')
if not web_page:
return web_page
import socket
try:
socket.getaddrinfo(web_page, 80)
return web_page
except:
return forms.ValidationError('Введите правильный адрес страници')
def clean_phone(self):
"""
phone checking
"""
cleaned_data = super(CompanyForm, 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('Введите правильный телефон')
def clean_fax(self):
"""
fax checking
"""
cleaned_data = super(CompanyForm, 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('Введите правильный факс')