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.
201 lines
8.6 KiB
201 lines
8.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
|
|
from django.forms.util import ErrorList
|
|
#models
|
|
from models import Webinar, CURRENCY
|
|
from theme.models import Theme
|
|
from organiser.models import Organiser
|
|
from accounts.models import User
|
|
from company.models import Company
|
|
from service.models import Service
|
|
from functions.files import check_tmp_files
|
|
from functions.form_check import translit_with_separator
|
|
|
|
|
|
#functions
|
|
from functions.translate import populate_all, fill_trans_fields_all
|
|
from functions.form_check import is_positive_integer
|
|
|
|
class WebinarCreateForm(forms.Form):
|
|
"""
|
|
Create Webinar form for creating webinar
|
|
|
|
__init__ uses for dynamic creates fields
|
|
|
|
save function saves data in Webinar object. If it doesnt exist create new object
|
|
"""
|
|
currencies = [(item, item) for item in CURRENCY]
|
|
|
|
data_begin = forms.DateTimeField(label='Дата и время начала')
|
|
#creates select input with empty choices cause it will be filled with ajax
|
|
tag = forms.MultipleChoiceField(label='Теги', required=False)
|
|
|
|
web_page = forms.CharField(label='Веб страница', required=False)
|
|
link = forms.CharField(label='Линк на регистрацию', required=False)
|
|
#
|
|
currency = forms.ChoiceField(label='Валюта', choices=currencies, required=False)
|
|
tax = forms.BooleanField(label='Налог включен', initial=True, required=False)
|
|
min_price = forms.CharField(label='Минимальная цена', required=False)
|
|
max_price = forms.CharField(label='Максимальная цена', required=False)
|
|
#field for comparing tmp files
|
|
key = forms.CharField(required=False, widget=forms.HiddenInput())
|
|
#
|
|
webinar_id = forms.CharField(required=False, widget=forms.HiddenInput())
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
"""
|
|
create dynamical translated fields fields
|
|
and fills select fields
|
|
"""
|
|
super(WebinarCreateForm, 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['main_title_%s' % code] = forms.CharField(label='Краткое описание',
|
|
required=False, widget=CKEditorWidget)
|
|
self.fields['programm_%s' % code] = forms.CharField(label='Описание',
|
|
required=False, widget=CKEditorWidget)
|
|
self.fields['discount_%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
|
|
themes = [(item.id, item.name) for item in Theme.objects.all()]
|
|
#!service has bitfield. uncomment when country data will be filled
|
|
#services = [(item.id, item.name) for item in Service.objects.all()]
|
|
|
|
self.fields['theme'] = forms.MultipleChoiceField(label='Тематики', choices=themes, required=False)
|
|
#self.fields['service'] = forms.MultipleChoiceField(label='Услуги', choices=services, required=False)
|
|
|
|
|
|
def save(self, id=None):
|
|
"""
|
|
changes Webinar model object with id = id
|
|
N/A add new Webinar model object
|
|
usage: form.save(obj) - if change webinar
|
|
form.save() - if add webinar
|
|
"""
|
|
data = self.cleaned_data
|
|
#create new webinar object or get exists
|
|
if not id:
|
|
webinar = Webinar()
|
|
else:
|
|
webinar = Webinar.objects.get(id=id)
|
|
webinar.theme.clear()
|
|
webinar.tag.clear()
|
|
|
|
#simple fields
|
|
webinar.url = translit_with_separator(data['name_ru']).lower()
|
|
webinar.data_begin = data['data_begin']
|
|
webinar.link = data['link']
|
|
webinar.web_page= data['web_page']
|
|
#
|
|
webinar.currency = data['currency']
|
|
webinar.tax = data['tax']
|
|
webinar.min_price = data['min_price']
|
|
webinar.max_price = data['max_price']
|
|
# uses because in the next loop data will be overwritten
|
|
webinar.save()
|
|
#fill manytomany fields
|
|
for item in data['theme']:
|
|
webinar.theme.add(item)
|
|
|
|
for item in data['tag']:
|
|
webinar.tag.add(item)
|
|
|
|
# uses because in the next loop data will be overwritten
|
|
webinar.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(Webinar, webinar, data, id, zero_fields)
|
|
#autopopulate
|
|
#populate empty fields and fields which was already populated
|
|
webinar_id = getattr(webinar, 'id')
|
|
populate_all(Webinar, data, webinar_id, zero_fields)
|
|
#save files
|
|
check_tmp_files(webinar, data['key'])
|
|
|
|
def clean(self):
|
|
id = self.cleaned_data.get('webinar_id')
|
|
name_ru = self.cleaned_data.get('name_ru')
|
|
|
|
webinar = Webinar.objects.filter(url=translit_with_separator(name_ru))
|
|
if webinar and str(webinar[0].id) != id:
|
|
msg = 'Вебинар с таким названием уже существует'
|
|
self._errors['name_ru'] = ErrorList([msg])
|
|
del self.cleaned_data['name_ru']
|
|
|
|
return self.cleaned_data
|
|
|
|
def clean_web_page(self):
|
|
"""
|
|
checking web_page
|
|
"""
|
|
cleaned_data = super(WebinarCreateForm, 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:
|
|
raise forms.ValidationError('Введите правильный адрес страници')
|
|
|
|
def clean_link(self):
|
|
"""
|
|
checking link
|
|
"""
|
|
cleaned_data = super(WebinarCreateForm, self).clean()
|
|
link = cleaned_data.get('link')
|
|
if not link:
|
|
return link
|
|
|
|
import socket
|
|
try:
|
|
socket.getaddrinfo(link, 80)
|
|
return link
|
|
except:
|
|
raise forms.ValidationError('Введите правильный адрес страници')
|
|
|
|
def clean_min_price(self):
|
|
"""
|
|
checking min_price
|
|
"""
|
|
cleaned_data = super(WebinarCreateForm, self).clean()
|
|
min_price = cleaned_data.get('min_price').strip()
|
|
return is_positive_integer(min_price)
|
|
|
|
def clean_max_price(self):
|
|
"""
|
|
checking max_price
|
|
"""
|
|
cleaned_data = super(WebinarCreateForm, self).clean()
|
|
max_price = cleaned_data.get('max_price').strip()
|
|
return is_positive_integer(max_price)
|
|
|
|
|
|
class WebinarChangeForm(WebinarCreateForm):
|
|
"""
|
|
add some fields to WebinarCreateForm
|
|
"""
|
|
organiser = forms.ModelMultipleChoiceField(label='Организаторы', queryset=Organiser.objects.all(), required=False)
|
|
company = forms.ModelMultipleChoiceField(label='Компании', queryset=Company.objects.all(), required=False)
|
|
users = forms.ModelMultipleChoiceField(label='Пользователи', queryset=User.objects.all(), required=False) |