forms.py 23.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
#-*- coding:utf-8 -*-

from django.core.exceptions import ValidationError
from django.forms import Textarea, TextInput, ModelMultipleChoiceField, \
    ModelChoiceField, ModelForm, Form, CharField, SelectMultiple, Select, \
    TypedMultipleChoiceField, HiddenInput, IntegerField, BooleanField, \
    ChoiceField
from common.forms import hidden_id
from common.util import GroupDict
from dictionary.models import Lexeme, LexemeInflectionPattern, Ending, \
    Pattern, PatternType, Classification, ClassificationValue, Vocabulary, \
    CrossReference, Qualifier, QualifierExclusionClass, Variant, \
    editable_vocabularies, editable_qualifiers, LexemeAttributeValue, \
    TableTemplate, BaseFormLabel, Gender, visible_vocabularies


def disable_field(field):
    if type(field.widget) in (Textarea, TextInput):
        field.widget.attrs['readonly'] = 'readonly'
    else:
        field.widget.attrs['disabled'] = 'disabled'

# ze StackOverflow, http://stackoverflow.com/questions/3737116/
class QualifiersField(ModelMultipleChoiceField):
    def __init__(self, **kwargs):
        super(QualifiersField, self).__init__(Qualifier.objects.none(),
            **kwargs)
        self.to_field_name = None #?

    def set_qualifiers(self, user, qualified=None, lexeme=None, types=None):
        # if qualified and qualified.id:
        #     if lexeme:
        #         vocabularies = lexeme.editable_vocabularies(user)
        #     else:
        #         vocabularies = qualified.editable_vocabularies(user)
        #     qualifiers = Qualifier.objects.filter(vocabulary__in=vocabularies)
        # else:
        qualifiers = editable_qualifiers(user)
        if types:
            qualifiers = qualifiers.filter(type__in=types)
        if not qualifiers:
            disable_field(self)
            return
        self.queryset = queryset = qualifiers.order_by('vocabulary', 'label')
        queryset = queryset.select_related('vocabulary')
        if qualified and qualified.pk:
            initial_qualifiers = qualified.qualifiers.all() & qualifiers
            self.initial = initial_qualifiers

        q_lists = GroupDict()
        for qualifier in queryset:
            q_lists.add(
                qualifier.vocabulary.id, (qualifier.id, qualifier.label))
        self.choices = sorted(q_lists.iteritems())


class QualifierField(ModelChoiceField):
    def __init__(self, **kwargs):
        qualifiers = Qualifier.objects.all()
        super(QualifierField, self).__init__(qualifiers, **kwargs)
        self.set_qualifiers(qualifiers)

    def set_qualifiers(self, qualifiers):
        if not qualifiers:
            disable_field(self)
            return
        qualifiers = qualifiers.select_related('vocabulary').order_by(
            'vocabulary', 'label')

        q_lists = GroupDict()
        for qualifier in qualifiers:
            q_lists.add(
                qualifier.vocabulary.id, (qualifier.id, qualifier.label))
        self.choices = sorted(q_lists.iteritems())


class LexemeEditForm(ModelForm):
    vocabularies = ModelMultipleChoiceField(
        queryset=Vocabulary.objects.none(), required=False)
    style_qualifiers = QualifiersField(
        required=False, label='kwal styl.',
        widget=SelectMultiple(attrs={'class': 'qualifiers'}))
    scope_qualifiers = QualifiersField(
        required=False, label='kwal. zakr.',
        widget=SelectMultiple(attrs={'class': 'qualifiers'}))
    new_owner = ModelChoiceField(
        queryset=Vocabulary.objects.none(), required=False)

    def __init__(self, user, editable=True, **kwargs):
        super(LexemeEditForm, self).__init__(**kwargs)
        editable_vocabs = editable_vocabularies(user)
        instance = getattr(self, 'instance', None)
        other_editable_vocabs = editable_vocabs.exclude(
            pk=instance.owner_vocabulary.pk)
        self.fields['entry'].required = True
        self.fields['new_owner'].queryset = editable_vocabs
        self.fields['vocabularies'].queryset = other_editable_vocabs
        self.fields['vocabularies'].initial = instance.visible_vocabularies(
            user)
        owner_choices = editable_vocabs.values_list('id', 'id')
        self.fields['new_owner'].choices = owner_choices
        if instance and instance.id:
            self.fields['new_owner'].initial = instance.owner_vocabulary
        if other_editable_vocabs.count() == 0:
            disable_field(self.fields['vocabularies'])
        self.fields['style_qualifiers'].set_qualifiers(
            user, instance, types=[Qualifier.TYPE_STYLE])
        self.fields['scope_qualifiers'].set_qualifiers(
            user, instance, types=[Qualifier.TYPE_SCOPE])
        if not editable and instance and instance.id:
            for name, field in self.fields.iteritems():
                if not name.startswith('qualifiers') and name != 'vocabularies':
                    disable_field(field)

    def clean_comment(self):
        data = self.cleaned_data['comment']
        return data.replace('\r', '')

    class Meta:
        model = Lexeme
        fields = (
            'part_of_speech',
            'entry',
            'status',
            'comment',
        )
        widgets = {
            'comment': Textarea(attrs={'cols': 40, 'rows': 5}),
        }

# abstract
class LexemeAttributeForm(Form):
    def __init__(self, attribute, required=True, **kwargs):
        super(LexemeAttributeForm, self).__init__(**kwargs)
        self.fields['value'].label = attribute.name
        self.fields['value'].required = attribute.required and required


class LexemeOpenAttributeForm(LexemeAttributeForm):
    value = CharField(widget=TextInput(attrs={'size': 40}))

    def __init__(self, attribute, initial_value=None, **kwargs):
        assert not attribute.closed and not attribute.multiple
        super(LexemeOpenAttributeForm, self).__init__(attribute, **kwargs)
        if initial_value is not None:
            self.fields['value'].initial = initial_value.value


class LexemeClosedAttributeForm(LexemeAttributeForm):
    value = ModelChoiceField(
        queryset=LexemeAttributeValue.objects.none(),
        widget=Select(attrs={'class': 'attr-value-select'}))

    def __init__(self, attribute, initial_value=None, **kwargs):
        assert attribute.closed and not attribute.multiple
        super(LexemeClosedAttributeForm, self).__init__(attribute, **kwargs)
        self.fields['value'].queryset = attribute.values
        self.fields['value'].initial = initial_value


class LexemeMultipleAttributeForm(LexemeAttributeForm):
    value = ModelMultipleChoiceField(
        queryset=LexemeAttributeValue.objects.none())

    def __init__(self, attribute, initial_value=None, **kwargs):
        assert attribute.closed and attribute.multiple
        super(LexemeMultipleAttributeForm, self).__init__(attribute, **kwargs)
        self.fields['value'].queryset = attribute.values
        self.fields['value'].initial = initial_value


class LIPEditForm(ModelForm):
    pattern_name = CharField(widget=TextInput(
        attrs={'class': 'pattern', 'size': '10'}), label=u'Wzór')
    qualifiers = QualifiersField(
        required=False, label=u'Kwal.',
        widget=SelectMultiple(attrs={'class': 'lip-qualifiers'}))
    lexical_class = CharField(widget=HiddenInput(), label=u'')

    def __init__(self, part_of_speech, lexeme, user, editable=True, index=None,
                 **kwargs):
        super(LIPEditForm, self).__init__(**kwargs)
        if part_of_speech.lexical_class_id != 'subst':
            self.fields['gender'].widget = HiddenInput()
            self.fields['gender'].label = ''
        instance = getattr(self, 'instance', None)
        self.fields['lexical_class'].initial = part_of_speech.lexical_class_id
        self.fields['qualifiers'].set_qualifiers(
            user, instance, lexeme,
            types=[Qualifier.TYPE_STYLE, Qualifier.TYPE_FORM])
        if instance and instance.id:
            self.fields['pattern_name'].initial = instance.pattern.name
            if not editable:
                for name, field in self.fields.iteritems():
                    if name != 'qualifiers':
                        disable_field(field)
        self.index = index

    def clean(self):
        cleaned_data = self.cleaned_data
        if 'pattern_name' in cleaned_data:
            try:
                pattern = Pattern.objects.get(name=cleaned_data['pattern_name'])
            except Pattern.DoesNotExist:
                raise ValidationError(u'Niepoprawna nazwa wzoru.')
            lc = cleaned_data['lexical_class']
            if pattern.type.lexical_class_id != lc:
                raise ValidationError(u'Wzór nie pasuje do części mowy.')
            cleaned_data['pattern'] = pattern
        return cleaned_data

    def save(self, *args, **kwargs):
        lip = self.instance
        lip.pattern = self.cleaned_data['pattern']
        if self.index:
            lip.index = self.index
        super(LIPEditForm, self).save(*args, **kwargs)
        lip.save()
        return lip

    class Meta:
        model = LexemeInflectionPattern
        fields = ['gender']
        widgets = {'gender': Select(attrs={'class': 'gender'})}


class ClassificationForm(Form):
    values = TypedMultipleChoiceField(
        choices=[], empty_value=None, coerce=int,
        widget=SelectMultiple(attrs={'class': 'classification-values'}))

    def __init__(self, classification, editable=True, values=None,
                 required=True, **kwargs):
        super(ClassificationForm, self).__init__(**kwargs)
        self.fields['values'].label = classification.name
        self.fields['values'].choices = classification.make_choices()
        self.fields['values'].required = required
        if values:
            self.fields['values'].initial = [value.pk for value in values]
        if not editable:
            for _name, field in self.fields.iteritems():
                disable_field(field)


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

    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']
        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']


class CrossReferenceForm(ModelForm):
    entry = CharField(label=u'hasło', widget=TextInput(attrs={
        'class': 'entry',
        'size': 12,
    }))
    homonym_number = IntegerField(label=u'hom.',
        widget=TextInput(attrs={
            'class': 'homonym-number',
            'readonly': 'readonly',
            'size': 1,
        }))

    def __init__(self, lexeme=None, pos=None, **kwargs):
        super(CrossReferenceForm, self).__init__(**kwargs)
        if lexeme is not None:
            if pos is None:
                pos = lexeme.part_of_speech
            crtypes = pos.crtype_to.all()
            type_choices = crtypes.values_list('pk', 'desc')
            self.fields['type'].widget.choices = type_choices
            self.fields['from_lexeme'].initial = lexeme.pk

    def clean(self):
        cleaned_data = self.cleaned_data
        from_lexeme = cleaned_data.get('from_lexeme')
        entry = cleaned_data.get('entry')
        hom = cleaned_data.get('homonym_number')
        cr_type = cleaned_data.get('type')
        try:
            to_lexeme = Lexeme.objects.get(
                entry=entry, homonym_number=hom, part_of_speech=cr_type.to_pos)
        except Lexeme.DoesNotExist:
            raise ValidationError(u'Wybrany leksem nie istnieje.')
        except Lexeme.MultipleObjectsReturned:
            # jeśli się zdarzy, to jest niespójność w danych
            raise ValidationError(u'Niejednoznaczny numer homonimu!')
        if from_lexeme and to_lexeme and cr_type:
            if cr_type.from_pos != from_lexeme.part_of_speech:
                raise ValidationError(u'Nieprawidłowa część mowy w odsyłaczu.')
        cleaned_data['to_lexeme'] = to_lexeme
        return cleaned_data

    def save(self, commit=True):
        cr = super(CrossReferenceForm, self).save(False)
        cr.to_lexeme = self.cleaned_data['to_lexeme']
        if commit:
            cr.save()
        return cr

    class Meta:
        model = CrossReference
        fields = ['type', 'from_lexeme']
        widgets = {
            'type': Select(attrs={'class': 'type'}),
            'from_lexeme': HiddenInput(),
        }


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 PatternEditForm(ModelForm):
    def __init__(self, editable=True, **kwargs):
        super(PatternEditForm, self).__init__(**kwargs)
        self.fields['type'].choices = PatternType.options()
        if not editable:
            instance = getattr(self, 'instance', None)
            if instance and instance.id:
                for name, field in self.fields.iteritems():
                    disable_field(field)

    class Meta:
        model = Pattern
        fields = (
            'type', 'name', 'example', 'basic_form_ending', 'status', 'comment')


class QualifierForm(Form):
    qualifiers = QualifiersField(
        required=False, label=u'',
        widget=SelectMultiple(attrs={'class': 'qualifiers'}))

    def __init__(self, user, qualified=None, editable=True,
                 **kwargs):
        super(QualifierForm, self).__init__(**kwargs)
        self.fields['qualifiers'].set_qualifiers(
            user, qualified, types=[Qualifier.TYPE_STYLE, Qualifier.TYPE_FORM])
        if not editable:
            disable_field(self.fields['qualifiers'])


class ExportForm(Form):
    vocabs = ModelMultipleChoiceField(
        queryset=Vocabulary.objects.all(), label=u'słowniki')
    antivocabs = ModelMultipleChoiceField(
        queryset=Vocabulary.objects.all(), label=u'antysłowniki',
        required=False)
    variant = ModelChoiceField(
        queryset=Variant.objects.filter(type=Variant.TYPE_EXPORT),
        label=u'wariant')
    refl = BooleanField(label=u'tagi z "refl"', required=False)
    commonness = BooleanField(label=u'etykiety pospolitości', required=False)
    #copyright = CharField(widget=Textarea(attrs={'cols': 80, 'rows': 40}))
    #excluding_qualifiers = QualifiersField(
    #  required=False, label=u'kwal. wykluczające')

    def __init__(self, user, **kwargs):
        super(ExportForm, self).__init__(**kwargs)
        self.fields['vocabs'].queryset = visible_vocabularies(user)
        self.fields['antivocabs'].queryset = visible_vocabularies(user)
        self.fields['vocabs'].help_text = u''
        self.fields['antivocabs'].help_text = u''


class MagicQualifierForm(Form):
    qualifier = QualifierField(label=u'kwal. leksemu')
    regex = CharField(label=u'wzorzec tagu', required=False)


ADD_REMOVE_CHOICES = (
    ('add', u'Dodaj'),
    ('remove', u'Usuń'),
)


class StatusActionForm(Form):
    action = ChoiceField(
        choices=[('set', u'ustaw')], label=u'',
        widget=Select(attrs={'class': 'action-choice'}))


class StatusValueForm(Form):
    value = ChoiceField(
        choices=Lexeme.STATUS_CHOICES, label=u'',
        widget=Select(attrs={'class': 'value-choice'}))

    def __init__(self, request, **kwargs):
        super(StatusValueForm, self).__init__(**kwargs)


class UsingVocabularyActionForm(Form):
    action = ChoiceField(
        choices=ADD_REMOVE_CHOICES, label=u'',
        widget=Select(attrs={'class': 'action-choice'}))


class VocabularyValueForm(Form):
    value = ModelChoiceField(
        queryset=Vocabulary.objects.none(), label=u'',
        widget=Select(attrs={'class': 'value-choice'}))

    def __init__(self, request, **kwargs):
        super(VocabularyValueForm, self).__init__(**kwargs)
        self.fields['value'].queryset = editable_vocabularies(request.user)


class LexemeQualifierActionForm(Form):
    action = ChoiceField(
        choices=ADD_REMOVE_CHOICES, label=u'',
        widget=Select(attrs={'class': 'action-choice'}))


class LexemeQualifierValueForm(Form):
    value = QualifierField(label=u'',
        widget=Select(attrs={'class': 'value-choice'}))

    def __init__(self, request, **kwargs):
        super(LexemeQualifierValueForm, self).__init__(**kwargs)
        self.fields['value'].set_qualifiers(editable_qualifiers(request.user))


ACTION_FIELDS = (
    ('status',
    (u'Status', StatusActionForm, StatusValueForm)),
    ('using_vocabulary',
    (u'Słownik używający', UsingVocabularyActionForm, VocabularyValueForm)),
    ('lexeme_qualifier',
    (u'Kwalifikator leksemu',
    LexemeQualifierActionForm, LexemeQualifierValueForm)),
)


class ActionFieldForm(Form):
    field = ChoiceField(
        choices=[(id, data[0]) for id, data in ACTION_FIELDS], label=u'',
        widget=Select(attrs={'class': 'field-choice'}))


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

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

class CSSClassForm(Form):
    css_class = ChoiceField(
        choices=CSS_CLASS_CHOICES, label='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'}))