forms.py 8.39 KB
# -*- coding: utf-8 -*-
from django.conf import settings
from django.core.exceptions import ValidationError
from django.forms import ModelForm, HiddenInput, Form, ModelChoiceField, \
    ModelMultipleChoiceField, SelectMultiple, Select, ChoiceField
from django.utils.translation import ugettext_lazy as _

from common.forms import hidden_id
from common.util import GroupDict
from dictionary.models import Classification, ClassificationValue, Qualifier, \
    QualifierExclusionClass, Lexeme, LexemeInflectionPattern, Ending, \
    Vocabulary, TableTemplate, PatternType, Gender, LexemeAttributeValue, \
    BaseFormLabel, MultilingualText

CSS_CLASS_CHOICES = (
    ('header', _(u'nagł.')),
    ('header-c', _(u'wyśr.')),
    ('data', _(u'dane')),
    ('blank', _(u'blank')),
)


class AddClassificationForm(ModelForm):
    det = hidden_id('classification_form')

    def save(self, *args, **kwargs):
        cl = super(AddClassificationForm, self)
        multi_name, created = MultilingualText.objects.get_or_create(
            text_id=cl.name)
        multi_name.add_translated_texts()
        cl.multilingual_name = multi_name
        cl.save()

    class Meta:
        model = Classification


class AddClassificationValueForm(ModelForm):
    det = hidden_id('value_form')

    def __init__(self, classification=None, **kwargs):
        super(AddClassificationValueForm, self).__init__(**kwargs)
        if classification is not None:
            parent_choices = (
                [('', _(u'<brak>'))] + classification.make_choices())
            self.fields['parent_node'].choices = parent_choices
            self.fields['classification'].initial = classification.pk

    class Meta:
        model = ClassificationValue
        fields = ['label', 'parent_node', 'classification']
        widgets = {
            'classification': HiddenInput(),
        }


class AddExclusionClassForm(ModelForm):
    det = hidden_id('add_exclusion_class')

    def __init__(self, vocabulary=None, **kwargs):
        super(AddExclusionClassForm, self).__init__(**kwargs)
        self.fields['vocabulary'].initial = vocabulary

    class Meta:
        model = QualifierExclusionClass
        widgets = {
            'vocabulary': HiddenInput(),
        }


class ExclusionClassForm(Form):
    det = hidden_id('remove_exclusion_class')
    ec = ModelChoiceField(
        queryset=QualifierExclusionClass.objects.all(), label=u'')  # dziura

    def __init__(self, queryset=None, **kwargs):
        super(ExclusionClassForm, self).__init__(**kwargs)
        if queryset:
            self.fields['ec'].queryset = queryset


class AddQualifierForm(ModelForm):
    det = hidden_id('add_qualifier')

    def __init__(self, vocabulary=None, **kwargs):
        super(AddQualifierForm, self).__init__(**kwargs)
        self.fields['vocabulary'].initial = vocabulary
        if vocabulary:
            self.fields['exclusion_class'].queryset = (
                QualifierExclusionClass.objects
                .filter(vocabulary=vocabulary).distinct())

    def clean(self):
        cleaned_data = self.cleaned_data
        ec = cleaned_data['exclusion_class']
        if ec:
            ec_vocab = ec.vocabulary
            if ec_vocab and ec_vocab != cleaned_data['vocabulary']:
                raise ValidationError(
                    _(u'Klasa wykluczania niezgodna ze słownikiem.'))
        return cleaned_data

    class Meta:
        model = Qualifier
        fields = ['label', 'exclusion_class', 'vocabulary', 'type']
        widgets = {
            'vocabulary': HiddenInput(),
        }


class ChangeClassForm(ModelForm):
    def __init__(self, **kwargs):
        super(ChangeClassForm, self).__init__(**kwargs)
        exclusion_classes = (
            self.instance.vocabulary.qualifierexclusionclass_set.all())
        self.fields['exclusion_class'].queryset = exclusion_classes

    def clean(self):
        ec = self.cleaned_data['exclusion_class']
        q = self.instance
        if ec:
            ec_qualifiers = ec.qualifier_set.all()
            if Lexeme.objects.filter(qualifiers=q).filter(
                    qualifiers__in=ec_qualifiers):
                raise ValidationError(_(u'Kolizja w klasie wykluczania'))
            if LexemeInflectionPattern.objects.filter(
                    qualifiers=q).filter(qualifiers__in=ec_qualifiers):
                raise ValidationError(_(u'Kolizja w klasie wykluczania'))
            if Ending.objects.filter(qualifiers=q).filter(
                    qualifiers__in=ec_qualifiers):
                raise ValidationError(_(u'Kolizja w klasie wykluczania'))
        return self.cleaned_data

    class Meta:
        model = Qualifier
        fields = ['exclusion_class', 'type']


class VocabularyForm(Form):
    det = hidden_id('vocabulary_form')
    vocabulary = ModelChoiceField(
        label=_(u"dodaj słownik"), queryset=Vocabulary.objects.none())
    classification = ModelChoiceField(
        widget=HiddenInput(), queryset=Classification.objects.all())

    def __init__(self, queryset, classification=None, **kwargs):
        super(VocabularyForm, self).__init__(**kwargs)
        self.fields['vocabulary'].queryset = queryset
        if classification:
            self.fields['classification'].initial = classification


class TemplateChoiceForm(Form):
    table_template = ModelChoiceField(
        TableTemplate.objects.none(), label=_(u'Szablon tabel'))

    def __init__(self, **kwargs):
        super(TemplateChoiceForm, self).__init__(**kwargs)
        choices = GroupDict()
        template_field = self.fields['table_template']
        for tt in TableTemplate.objects.order_by('variant', 'name'):
            choices.add(tt.variant.id, (tt.id, tt))
        template_field.choices = sorted(choices.iteritems())


class CellRestrictionsForm(Form):
    pattern_types = ModelMultipleChoiceField(
        queryset=PatternType.objects.none(), label=u'',
        widget=SelectMultiple(attrs={'class': 'pattern-types-select'}))

    # wybrane/dostępne typy wzorów
    def __init__(self, sel_pt, av_pt, **kwargs):
        super(CellRestrictionsForm, self).__init__(**kwargs)
        self.fields['pattern_types'].queryset = av_pt
        self.fields['pattern_types'].initial = sel_pt


class GenderForm(Form):
    genders = ModelMultipleChoiceField(
        queryset=Gender.objects.all(), label=u'',
        widget=SelectMultiple(attrs={'class': 'gender-select'}))

    def __init__(self, initial=None, **kwargs):
        super(GenderForm, self).__init__(**kwargs)
        if initial:
            self.fields['genders'].initial = initial
        else:
            self.fields['genders'].initial = self.fields['genders'].queryset


class AttributeValuesForm(Form):
    values = ModelMultipleChoiceField(
        queryset=LexemeAttributeValue.objects.none(),
        widget=SelectMultiple(attrs={'class': 'attrs-select'}))

    def __init__(self, attribute, initial=None, **kwargs):
        assert attribute.closed and not attribute.multiple
        super(AttributeValuesForm, self).__init__(**kwargs)
        self.fields['values'].label = attribute.name
        self.fields['values'].queryset = attribute.values
        if initial is None:
            initial = attribute.values.all()
        self.fields['values'].initial = initial


class BaseFormLabelForm(Form):
    base_form_label = ModelChoiceField(
        queryset=BaseFormLabel.objects.none(), label=u'',
        widget=Select(attrs={'class': 'bfl-select'}))

    def __init__(self, bfls, initial=None, **kwargs):
        super(BaseFormLabelForm, self).__init__(**kwargs)
        self.fields['base_form_label'].queryset = bfls
        self.fields['base_form_label'].initial = initial


class CSSClassForm(Form):
    css_class = ChoiceField(
        choices=CSS_CLASS_CHOICES, label=_(u'klasa'),
        widget=Select(attrs={'class': 'css-class-select'}))

    def __init__(self, initial=None, **kwargs):
        super(CSSClassForm, self).__init__(**kwargs)
        self.fields['css_class'].initial = initial


class TemplatePreviewForm(Form):
    pattern_type = ModelChoiceField(
        queryset=PatternType.objects.none(), label=_(u'typ wzoru'),
        widget=Select(attrs={'class': 'pattern-type-select'}))

    def __init__(self, pattern_types, **kwargs):
        super(TemplatePreviewForm, self).__init__(**kwargs)
        self.fields['pattern_type'].queryset = pattern_types


class TemplatePreviewGenderForm(Form):
    gender = ModelChoiceField(
        queryset=Gender.objects.all(), label=_(u'rodzaj'),
        widget=Select(attrs={'class': 'gender-select'}))