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.
 
 
 
 
 
 

524 lines
18 KiB

# -*- coding: utf-8 -*-
import json
import re
from django import forms
from django.utils import translation
from django.utils.translation import ugettext_lazy as _
from django.core.urlresolvers import reverse
from ckeditor.widgets import CKEditorWidget
from expobanner.models import (
URL,
Banner,
BannerGroup,
Customer,
MainPage,
Paid,
Top
)
from functions.forms import FieldsetMixin
from functions.forms import ML_ModelMultipleChoiceField
from functions.model_utils import EnumChoices
from city.models import City
from country.models import Country
from conference.models import Conference
from exposition.models import Exposition
from place_conference.models import PlaceConference
from place_exposition.models import PlaceExposition
from theme.models import Tag, Theme
class UrlCreateForm(forms.ModelForm):
verbose = _(u'Создать урл')
class Meta:
model = URL
exclude = ['created_at', 'updated_at', 'sites']
class BannerCreateGroupForm(forms.ModelForm):
verbose = _(u'Создать групу')
class Meta:
model = BannerGroup
exclude = ['created_at', 'updated_at', 'speed']
class BannerGroupUpdateForm(BannerCreateGroupForm):
verbose = _(u'Изменить групу')
class Meta:
model = BannerGroup
exclude = ['created_at', 'updated_at', 'slug', 'speed']
class BannerCreateForm(forms.ModelForm):
verbose = _(u'Создать банер')
text = forms.CharField(label=u'Текст', required=False, widget=CKEditorWidget)
class Meta:
model = Banner
exclude = ['created_at', 'updated_at', 'paid', 'stat_pswd', 'cookie', 'link']
class CustomerCreateForm(forms.ModelForm):
verbose = _(u'Создание заказчика')
class Meta:
model = Customer
widgets = {
'description': CKEditorWidget
}
class BannerLinkCreateForm(forms.ModelForm):
verbose = _(u'Отслеживаемую ссылку')
class Meta:
model = Banner
fields = ['public', 'alt', 'url']
exclude = ['created_at', 'updated_at', 'often', 'paid', 'stat_pswd', 'cookie', 'link', 'customer']
def save(self, commit=True):
banner = super(BannerLinkCreateForm, self).save(commit=False)
if commit:
banner.link =True
banner.save()
return banner
class ClientStatForm(forms.Form):
stat_pswd = forms.CharField(label=_(u'Введите пароль:'))
def check_pass(self, obj):
pswd = self.cleaned_data['stat_pswd']
return obj.stat_pswd == pswd
class BasePaidCreateForm(forms.ModelForm):
tickets = forms.URLField(label=_(u'Линк на билеты'))
class Meta:
model = Paid
fields = ['logo', 'organiser', 'public']
def get_target_obj(self):
raise NotImplementedError('You must implement this method in children class')
def save(self, commit=True):
paid = super(BasePaidCreateForm, self).save(commit=False)
if commit:
# obj = self.cleaned_data['exposition']
obj = self.get_target_obj()
tickets = self.cleaned_data['tickets']
tickets_link = Banner.objects.create_for_paid(obj, tickets, 'tickets')
participation = self.cleaned_data.get('participation', None)
if participation:
participation_link = Banner.objects.create_for_paid(obj, participation, 'participation')
paid.participation = participation_link
official = self.cleaned_data['official']
official_link = Banner.objects.create_for_paid(obj, official, 'official')
catalog = obj.get_permanent_url()
catalog_link = Banner.objects.create_for_paid(obj, catalog, 'catalog')
participants_list = self.cleaned_data.get('participants_list')
if participants_list:
participants_list_link = Banner.objects.create_for_paid(
obj, participants_list, 'participants_list'
)
paid.participants_list = participants_list_link
paid.tickets = tickets_link
paid.official = official_link
paid.catalog = catalog_link
paid.kind = self.kind # Exposition (1) or Conference (2)
paid.save()
obj.paid_new = paid
obj.save()
return paid
class PaidCreateForm(BasePaidCreateForm):
kind = 1
verbose = _(u'Создать проплаченую выставку')
participation = forms.URLField(label=_(u'Линк на участие'))
official = forms.URLField(label=_(u'Линк на официальный сайт'))
participants_list = forms.URLField(label=_(u'Линк на список участников'))
exposition = forms.CharField(label=_(u'Выставка'), widget=forms.HiddenInput())
def get_target_obj(self):
return self.cleaned_data['exposition']
def clean_exposition(self):
expo_id = self.cleaned_data['exposition']
try:
expo = Exposition.objects.get(id=expo_id)
except Exposition.DoesNotExist:
raise forms.ValidationError(_(u'Такой выставки не существует'))
return expo
class PaidConfCreateForm(BasePaidCreateForm):
kind = 2
verbose = _(u'Создать проплаченую конференцию')
official = forms.URLField(label=_(u'Линк на официальный сайт'))
conference = forms.CharField(label=_(u'Конференция'), widget=forms.HiddenInput())
def get_target_obj(self):
return self.cleaned_data['conference']
def clean_conference(self):
conference_id = self.cleaned_data['conference']
try:
expo = Conference.objects.get(id=conference_id)
except Conference.DoesNotExist:
raise forms.ValidationError(_(u'Такой конференции не существует'))
return expo
class MainCreateForm(forms.ModelForm):
verbose = _(u'Добавить выставку на главную')
exposition = forms.CharField(label=_(u'Выставка'), widget=forms.HiddenInput())
class Meta:
model = MainPage
fields = ['position', 'public']
def save(self, commit=True):
main = super(MainCreateForm, self).save(commit=False)
if commit:
expo = self.cleaned_data['exposition']
link = expo.get_permanent_url()
link_b = Banner.objects.create_for_paid(expo, link, 'main_page_link')
main.link = link_b
main.save()
expo.main = main
expo.save()
return main
def clean_exposition(self):
expo_id = self.cleaned_data['exposition']
try:
expo = Exposition.objects.get(id=expo_id)
except Exposition.DoesNotExist:
raise forms.ValidationError(_(u'Такой выставки не существует'))
return expo
class MainConfCreateForm(forms.ModelForm):
verbose = _(u'Добавить конференцию на главную')
conf = forms.CharField(label=_(u'Конференция'), widget=forms.HiddenInput())
class Meta:
model = MainPage
fields = ['position', 'public']
def save(self, commit=True):
main = super(MainConfCreateForm, self).save(commit=False)
if commit:
conf = self.cleaned_data['conf']
link = conf.get_permanent_url()
link_b = Banner.objects.create_for_paid(conf, link, 'main_page_link')
main.link = link_b
main.save()
conf.main = main
conf.save()
return main
def clean_conf(self):
conf_id = self.cleaned_data['conf']
try:
conf = Conference.objects.get(id=conf_id)
except Conference.DoesNotExist:
raise forms.ValidationError(_(u'Такой конференции не существует'))
return conf
class BasePaidUpdateForm(forms.ModelForm):
tickets = forms.URLField(label=_(u'Линк на билеты'))
class Meta:
model = Paid
fields = ['logo', 'organiser', 'public']
def save(self, commit=True):
paid = super(BasePaidUpdateForm, self).save(commit=False)
if commit:
tickets = self.cleaned_data['tickets']
b_tickets = paid.tickets
if tickets != b_tickets.url:
b_tickets.url = tickets
b_tickets.save()
participation = self.cleaned_data.get('participation', None)
if participation:
b_participation = paid.participation
if participation != b_participation.url:
b_participation.url = participation
b_participation.save()
official = self.cleaned_data['official']
b_official = paid.official
if official != b_official.url:
b_official.url = official
b_official.save()
participants_list = self.cleaned_data.get('participants_list')
if participants_list:
b_participants_list = paid.participants_list
if b_participants_list is None:
participants_list_link = Banner.objects.create_for_paid(
self.instance.get_event(),
participants_list,
'participants_list'
)
paid.participants_list = participants_list_link
elif participants_list != b_participants_list.url:
b_participants_list.url = participants_list
b_participants_list.save()
paid.save()
return paid
class PaidUpdateForm(BasePaidUpdateForm):
participation = forms.URLField(label=_(u'Линк на участие'))
official = forms.URLField(label=_(u'Линк на официальный сайт'))
participants_list = forms.URLField(label=_(u'Линк на список участников'))
class Meta:
model = Paid
fields = ['logo', 'organiser', 'public']
class PaidConfUpdateForm(BasePaidUpdateForm):
official = forms.URLField(label=_(u'Линк на официальный сайт'))
class Meta:
model = Paid
fields = ['logo', 'organiser', 'public']
class MainUpdateForm(forms.ModelForm):
class Meta:
model = MainPage
fields = ['position', 'public']
class TopMixinForm(forms.ModelForm, FieldsetMixin):
cities = forms.CharField(label=_(u'Город'), widget=forms.HiddenInput() ,required=False)
country = forms.MultipleChoiceField(
label=u'Страны',
choices=[[x.pk, x.name] for x in list(set(Country.objects.all()))],
required=False
)
class Meta:
model = Top
fields = [
'position', 'theme', 'country', 'fr', 'to', 'months',
'cities', 'years']
fieldsets = [
{'title': '',
'class': '',
'fields': ['position', 'theme', 'country', 'fr', 'to']},
{'title': _(u'Топ города'),
'class': '',
'fields': ['cities', 'months', 'years']}
]
def __init__(self, *args, **kwargs):
super(TopMixinForm, self).__init__(*args, **kwargs)
instance = getattr(self, 'instance', None)
if instance.pk:
lang = translation.get_language()
self.fields['cities'].widget.attrs['data-init-text'] =\
json.dumps([{'id': item.id, 'text': item.name} for item in list(instance.cities.filter(translations__language_code=lang))])
def clean_cities(self):
cities = self.cleaned_data.get('cities')
if cities:
res = []
for id in cities.split(','):
try:
res.append(int(id))
except ValueError:
continue
return City.objects.filter(id__in=res)
else:
return City.objects.none()
def save(self, commit=True):
top = super(TopMixinForm, self).save(commit=False)
# Prepare a 'save_m2m' method for the form,
old_save_m2m = self.save_m2m
def save_m2m():
print 111111111
print self
print self.cleaned_data['country']
old_save_m2m()
# This is where we actually link the pizza with toppings
top.theme.clear()
for theme in self.cleaned_data['theme']:
top.theme.add(theme)
top.country.clear()
for country in self.cleaned_data['country']:
top.country.add(country)
top.cities.clear()
for city in self.cleaned_data['cities']:
top.cities.add(city)
self.save_m2m = save_m2m
if commit:
top.save()
self.save_m2m()
return top
class TopCreateForm(TopMixinForm):
verbose = _(u'Создать событие в топе')
TYPES = EnumChoices(
EXPO=(1, _(u'Выставка')),
CONF=(2, _(u'Конференция')),
)
event_type = forms.TypedChoiceField(label=_(u'Тип события'), choices=TYPES, initial=TYPES.EXPO, coerce=int)
event = forms.CharField(label=_(u'Событие'), widget=forms.HiddenInput())
country = forms.MultipleChoiceField(label=_(u'Страна'), choices=[('', ' ')] + [(c.id, c.name) for c in Country.objects.language().all()], required=False)
theme = forms.MultipleChoiceField(label=_(u'Тематика'), required=False,
choices=[('', ' ')] + [(item.id, item.name) for item in Theme.objects.language().all()])
#excluded_cities = forms.CharField(label=u'Город', widget=forms.HiddenInput(), required=False)
#excluded_tags = forms.CharField(label=u'Тег', widget=forms.HiddenInput(), required=False)
class Meta(TopMixinForm.Meta):
fieldsets = [
{'title': '',
'class': '',
'fields': ['position', 'theme', 'country', 'fr', 'to', 'event_type', 'event']},
{'title': _(u'Топ города'),
'class': '',
'fields': ['cities', 'months', 'years']}
]
def save(self, commit=True):
top = super(TopCreateForm, self).save(commit=False)
if commit:
event = self.cleaned_data['event']
link = event.get_permanent_url()
link_b = Banner.objects.create_for_paid(event, link, 'top_link')
top.link = link_b
top.catalog = {1: 'expo', 2: 'conference'}.get(self.cleaned_data.get('event_type'))
top.save()
self.save_m2m()
event.top = top
event.save()
return top
def clean_theme(self):
theme_ids = self.cleaned_data['theme']
if theme_ids:
return Theme.objects.filter(id__in=theme_ids)
return Theme.objects.none()
def clean_country(self):
country_ids = self.cleaned_data['country']
if country_ids:
return Country.objects.filter(id__in=country_ids)
return Country.objects.none()
def clean_event(self):
event_id = self.cleaned_data['event']
event_type = self.cleaned_data['event_type']
model = {1: Exposition, 2: Conference}.get(event_type)
try:
event = model.objects.get(id=event_id)
except model.DoesNotExist:
raise forms.ValidationError(_(u'Такого события не существует'))
return event
class TopUpdateForm(TopMixinForm):
verbose = _(u'Изменить событие')
class TopPlaceFormMixin(forms.ModelForm):
class Meta:
model = Top
fields = ['position', 'fr', 'to', 'cities', 'country', 'base_catalog']
cities = ML_ModelMultipleChoiceField(label=_(u'Города'),
queryset=City.objects.all(), required=False)
country = ML_ModelMultipleChoiceField(label=_(u'Страны'),
queryset=Country.objects.all(), required=False)
def __init__(self, *args, **kwargs):
super(TopPlaceFormMixin, self).__init__(*args, **kwargs)
lang = translation.get_language()
where = " `{db_table}_translation`.`language_code` = '{lang}' "
for name, field in self.fields.iteritems():
if hasattr(field, 'queryset'):
model = field.queryset.model.__name__.lower()
field.widget.attrs.update({
'data-ajax-url': reverse('admin_{model}_search'.format(model=model)),
'select2': 'true',
'multiple': 'true',
})
field.queryset = field.queryset.model.objects.language(lang).all().order_by('name')\
.extra(where=[
where.format(db_table=field.queryset.model._meta.db_table, lang=lang)
])
field.widget.choices = field.choices
class TopPlaceCreateForm(TopPlaceFormMixin):
verbose = _(u'Создать ТОП место')
place_models = {'c': PlaceConference, 'e': PlaceExposition}
place = forms.CharField(label=_(u'Место'), widget=forms.Select())
def __init__(self, *args, **kwargs):
super(TopPlaceCreateForm, self).__init__(*args, **kwargs)
self.fields['place'].widget.attrs.update({
'data-ajax-url': reverse('admin_place_search'),
'select2': 'true',
})
def clean_place(self):
place = self.cleaned_data.get('place')
r = re.compile(r'^(?P<type>c|e)(?P<pk>\d+)$')
match = r.match(place)
if not match:
raise forms.ValidationError(_(u'Введены неверные данные'))
model = self.place_models.get(match.group('type'))
place_id = match.group('pk')
try:
place = model.objects.get(pk=place_id)
except model.DoesNotExist:
raise forms.ValidationError(_(u'Такого места не существует'))
return place
def save(self, commit=True):
top = super(TopPlaceCreateForm, self).save(commit=False)
if commit:
place = self.cleaned_data['place']
link = place.get_permanent_url()
link_b = Banner.objects.create_for_paid(place, link, 'top_link')
top.link = link_b
top.catalog = 'places'
top.save()
self.save_m2m()
place.top = top
place.save()
return top
class TopPlaceUpdateForm(TopPlaceFormMixin):
verbose = _(u'Изменить ТОП место')