forms.py 28.9 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 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
from random import randint

from django import forms

from django.db.models import OneToOneField, ForeignKey, CharField, ManyToManyField, Q

from crispy_forms.helper import FormHelper
import crispy_forms.bootstrap as bootstrap
import crispy_forms.layout as layout

from connections.models import Entry, POS, Status, SchemaHook
from syntax.models import (
    Schema, SchemaOpinion, InherentSie, Negativity, Predicativity, Aspect,
    Position, SyntacticFunction, Control, PredicativeControl,
)
from syntax.models_phrase import PhraseType, EmptyAttributes

from semantics.models import (
    Frame, FrameOpinion,
    Argument, SemanticRole, RoleAttribute,
    PredefinedSelectionalPreference, RelationalSelectionalPreference,
)

from meanings.models import Synset

from .form_fields.generic_fields import (
    RangeFilter,
    RegexFilter,
    ModelChoiceFilter,
    MultipleChoiceFilter,
    ModelMultipleChoiceFilter,
    OperatorField,
    SwitchField,
)

from .form_fields.specialised_fields import (
    PhraseoFilter,
    PhraseTypeFilter,
    ArgumentFilter,
    PredefinedPreferenceFilter,
    RelationalPreferenceFilter,
    #SynsetPreferenceFilter,
)

from .form_fields.query_managers import SingleValueQueryManager

# TODO better to import this from the importer, the web app should not be aware of the importer! :)
from importer.PhraseAttributes import attrs_helpers

from . import polish_strings


# TODO get_queries probably needs refactoring now that QueryForm is subclassed
class QueryForm(forms.Form):
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-sm-2'
        self.helper.field_class = 'col-sm-10'
        self.helper.attrs = { 'data_formtype' : 'unknown' }
    
    @staticmethod
    def get_child_form_prefix(child_form):
        raise NotImplementedError
    
    def get_queries(self):
        queries = []
        for key, value in self.cleaned_data.items():
            #print('========', key, value)
            if value and not key.startswith('operator') and not key.startswith('filter'):
                #if filter_type is not None and key.split('_')[0] != filter_type:
                #    continue
                form_field = self.fields[key]
                operator_key = 'operator_{}'.format(key)
                # TODO conjunction variable is only needed if filter_type is None?
                conjunction = self.cleaned_data.get(operator_key)
                if conjunction is None:
                    conjunction = form_field.query_manager.default_conjunction
                queries += form_field.query_manager.make_queries(value, conjunction)
        return queries
    
    @classmethod
    def make_field(cls, field_name):
        field_object = cls.base_fields[field_name]
        return field_object.layout(field_name)

def or_button(button_label):
    return bootstrap.StrictButton('+ Lub ({})'.format(button_label), css_class='or-button btn-sm btn-info')

def remove_button(label):
    return bootstrap.StrictButton(label, css_class='remove-button btn-sm btn-warning')

def and_or_form_creator(button_label, field_name=None, data_add=None, *args, **kwargs):
    add_button = None
    data_add = 'switch' if data_add is None else data_add
    if field_name is not None:
        add_button = bootstrap.FieldWithButtons(field_name, bootstrap.StrictButton('+ Dodaj', css_class='add-button btn-sm btn-success', data_add=data_add, *args, **kwargs))
    else:
        add_button = bootstrap.StrictButton('+ {}'.format(button_label), css_class='add-button btn-sm btn-success', data_add=data_add, *args, **kwargs)
    return [
        #layout.HTML('<div class="and-or-forms py-1 pl-1 mb-1 border-top border-bottom border-danger" data-formtype="{}">'.format(data_add)),
        layout.HTML('<div class="and-or-forms py-1 pl-1 mb-1" data-formtype="{}">'.format(data_add)),
        add_button,
        or_button(button_label),
        layout.HTML('</div>'),
    ]
    

'''
class MainEntryForm(QueryForm):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper.form_method = 'get'
        # TODO remove if this form is to be used with different views
        self.helper.form_action = 'entries:get_entries'
        self.helper.form_id = 'main-form'
        self.helper.attrs = { 'data_formtype' : 'entry-main' }
        self.model_class = Entry
        
        components = []
        components.append(layout.Submit('main-submit', 'Filtruj'))
        self.helper.layout = layout.Layout(*components)
    
    @staticmethod
    def get_child_form_prefix(child_form):
        if child_form.model_class == Schema:
            return 'subentries__schemata__in'
        if child_form.model_class == Frame:
            return 'subentries__schema_hooks__argument_connections__argument__frame__in'
        raise KeyError(type(child_form))
'''

class EntryForm(QueryForm):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        #self.helper.form_method = 'get'
        # TODO remove if this form is to be used with different views
        self.helper.form_action = 'entries:get_entries'
        self.helper.form_id = 'main-form'
        self.helper.attrs = { 'data_formtype' : 'entry' }
        self.model_class = Entry
        
        entry_components = [
            self.make_field('lemma'),
            self.make_field('pos'),
            self.make_field('phraseology'),
            self.make_field('status'),
        ]
        
        schema_components = [
            self.make_field('num_schemata'),
        ] + \
        and_or_form_creator('Schemat', data_add='schema') + \
        [
            self.make_field('filter_schemata'),
        ] + \
        and_or_form_creator('Fraza', field_name='phrase_type', data_prefix='phrase_')
        
        frame_components = [
            self.make_field('num_frames'),
        ] + \
        and_or_form_creator('Rama', data_add='frame') + \
        [
            self.make_field('filter_frames'),
        ]
        
        components = [
            layout.Fieldset('Własności haseł', *entry_components),
            layout.Fieldset('Własności składniowe', *schema_components),
            layout.Fieldset('Własności semantyczne', *frame_components),
            layout.Submit('main-submit', 'Filtruj'),
            layout.Reset('main-reset', 'Wyczyść'),
        ]
        
        self.helper.layout = layout.Layout(*components)
    
    lemma = RegexFilter(
        label='Lemat',
        lookup='name',
        max_length=200,
        autocomplete='lemma',
    )
    pos = ModelMultipleChoiceFilter(
        label='Część mowy',
        queryset=POS.objects.exclude(tag='unk'),
        key='tag',
        human_values=polish_strings.POS,
        lookup='pos',
    )
    phraseology = PhraseoFilter()
    status = ModelMultipleChoiceFilter(
        label ='Status',
        queryset=Status.objects.all().order_by('-priority'),
        key = 'key',
        lookup='status',
    )
    num_schemata = RangeFilter(
        label='Liczba schematów',
        lookup='schemata_count',
    )
    num_frames = RangeFilter(
        label='Liczba ram',
        lookup='frames_count',
    )
    phrase_type = PhraseTypeFilter(help_text='Typ frazy występujący w haśle.')
    filter_schemata = SwitchField('Ukryj niepasujące schematy')
    filter_frames = SwitchField('Ukryj niepasujące ramy')
    
    @staticmethod
    def get_child_form_prefix(child_form):
        if child_form.model_class == Schema:
            return 'subentries__schemata__in'
        if child_form.model_class == PhraseType:
            return 'subentries__schemata__positions__phrase_types__in'
        if child_form.model_class == Frame:
            return 'subentries__schema_hooks__argument_connections__argument__frame__in'
        raise KeyError(type(child_form))


# for forms that can appear multiple times in the query consrtuctor field
# (e.g. a phrase form), create a separate form class for each form ‘instance’,
# with globally unique field names to ensure proper javascript behaviour
# and retrieving the field values in views
class FormFactory(object):
    
    @staticmethod
    def unique_number():
        return randint(1000, 12345678)
    
    @staticmethod
    def unique_name(field_name, unique_number):
        return '{}_{}'.format(field_name, unique_number)
    
    @staticmethod
    def make_helper_attrs(form_type, unique_number):
        return { 'data_formtype' : form_type , 'data_formnumber' : unique_number }
    
    @staticmethod
    def make_layout(title, components):
        return layout.Layout(layout.Fieldset(
            '{} <button class="btn remove-button btn-sm btn-warning" type="button">Usuń</button>'.format(title),
            *components
        ))
    
    @classmethod    
    def get_form(cls, unique_number=None, *args, **kwargs):
        unique_number = cls.unique_number() if unique_number is None else unique_number
        form_class = cls.make_form_class(n=unique_number)
        for field_name, field_maker in cls.field_makers:
            form_class.base_fields[FormFactory.unique_name(field_name, unique_number)] = field_maker()
        return form_class(*args, **kwargs)
    
    # n – unique number for this form used for creating globally unique field names
    @classmethod
    def make_form_class(cls, n):
        raise NotImplementedError

class SchemaFormFactory(FormFactory):
    
    field_makers = (
        (
            'opinion',
            lambda: ModelMultipleChoiceFilter(
                label='Opinia o schemacie',
                queryset=SchemaOpinion.objects.all(),
                key='key',
                human_values=polish_strings.SCHEMA_OPINION,
                lookup='opinion',
                #initial=SchemaOpinion.objects.filter(key__in=('col', 'vul')),
            )
        ), 
        #(
        #    'operator_opinion',
        #    lambda: OperatorField()
        #),
        (
            'type',
            lambda: MultipleChoiceFilter(
                label='Typ',
                choices=((False, 'zwykły'), (True, 'frazeologiczny'),),
                lookup='phraseologic',
            )
        ),
        #(
        #    'operator_type',
        #    lambda: OperatorField()
        #),
        (
            'sie',
            lambda: ModelMultipleChoiceFilter(
                label='Zwrotność',
                queryset=InherentSie.objects.all().order_by('-priority'),
                key='name',
                human_values=polish_strings.TRUE_FALSE_YES_NO,
                lookup='inherent_sie',
            )
        ),
        #(
        #    'operator_sie',
        #    lambda: OperatorField()
        #),
        #(
        #    'neg',
        #    lambda: ModelMultipleChoiceFilter(
        #        label='Negatywność',
        #        queryset=Negativity.objects.exclude(name='').order_by('-priority'),
        #        key='name',
        #        human_values=polish_strings.NEGATION,
        #        entry_lookup='subentries__negativity',
        #        # both Schema and Entry have the same related name for Subentry:
        #        # can use the same lookup path
        #        object_lookup=None,
        #    )
        #),
        #(
        #    'operator_neg',
        #    lambda: OperatorField()
        #),
        #(
        #    'pred',
        #    lambda: ModelMultipleChoiceFilter(
        #        label='Predykatywność',
        #        queryset=Predicativity.objects.all().order_by('-priority'),
        #        key='name',
        #        human_values=polish_strings.TRUE_FALSE_YES_NO,
        #        entry_lookup='subentries__predicativity',
        #        # both Schema and Entry have the same related name for Subentry:
        #        # can use the same lookup path
        #        object_lookup=None,
        #    )
        #),
        #(
        #    'operator_pred',
        #    lambda: OperatorField()
        #),
        #(
        #    'aspect',
        #    lambda: ModelMultipleChoiceFilter(
        #        label='Aspekt',
        #        queryset=Aspect.objects.exclude(name='').exclude(name='_').order_by('-priority'),
        #        key='name',
        #        human_values=polish_strings.ASPECT,
        #        entry_lookup='subentries__aspect',
        #        # both Schema and Entry have the same related name for Subentry:
        #        # can use the same lookup path
        #        object_lookup=None,
        #    )
        #),
        #(
        #    'operator_aspect',
        #    lambda: OperatorField()
        #),
        #phrase = RegexFilter(
        #label='Fraza',
        #max_length=200,
        ##initial='np.* !& !np.* | xp.*',
        #lookup='positions__phrase_types__text_rep',
        #additional_operators=True,
        #autocomplete='phrasetype',
        #)
        #(
        #    'num_positions',
        #    lambda: RangeFilter(
        #        label='Liczba pozycyj',
        #        entry_lookup='subentries__schemata__positions_count',
        #        object_lookup='positions_count',
        #    )
        #),
        #(
        #    'num_phrase_types',
        #    lambda: RangeFilter(
        #        label='Liczba typów fraz w pozycji',
        #        entry_lookup='subentries__schemata__positions__phrases_count',
        #        object_lookup='positions__phrases_count',
        #    )
        #),
    )
    
    @classmethod
    def make_form_class(cls, n):

        class SchemaForm(QueryForm):

            def __init__(self, *args, **kwargs):
                super().__init__(*args, **kwargs)
                self.helper.attrs = cls.make_helper_attrs('schema', n)
                self.model_class = Schema
                
                components = [
                    #remove_button('Usuń schemat'),
                    self.make_field(cls.unique_name('opinion', n)),
                    #self.make_field(cls.unique_name('operator_opinion', n)),
                    self.make_field(cls.unique_name('type', n)),
                    self.make_field(cls.unique_name('sie', n)),
                    #self.make_field(cls.unique_name('phrase', n)),
                ] + \
                    and_or_form_creator('Pozycja', data_add='position')
                self.helper.layout = cls.make_layout('Schemat składniowy', components)
            
            @staticmethod
            def get_child_form_prefix(child_form):
                if child_form.model_class == Position:
                    return 'positions__in'
                raise KeyError(type(child_form))
        
        return SchemaForm


class PositionFormFactory(FormFactory):
    
    field_makers = (
        (
            'gram_function',
            lambda: ModelMultipleChoiceFilter(
                label='Funkcja gramatyczna',
                queryset=SyntacticFunction.objects.all(),
                key='name',
                lookup='function',
            )
        ),
        (
            'control',
            lambda: ModelMultipleChoiceFilter(
                label='Kontrola',
                queryset=Control.objects.all(),
                key='name',
                lookup='control',
            )
        ),
        (
            'pred_control',
            lambda: ModelMultipleChoiceFilter(
                label='Kontrola predykatywna',
                queryset=PredicativeControl.objects.all(),
                key='name',
                lookup='pred_control',
            )
        ),
        (
            'phrase_type',
            lambda: PhraseTypeFilter(help_text='Typ frazy występujący na pozycji.')
        ),
    )
    
    @classmethod
    def make_form_class(cls, n):
        
        class PositionForm(QueryForm):

            def __init__(self, *args, **kwargs):
                super().__init__(*args, **kwargs)
                self.helper.attrs = cls.make_helper_attrs('position', n)
                self.model_class = Position
                
                components = [
                    self.make_field(cls.unique_name('gram_function', n)),
                    self.make_field(cls.unique_name('control', n)),
                    self.make_field(cls.unique_name('pred_control', n)),
                ] + \
                    and_or_form_creator('Fraza', field_name=(cls.unique_name('phrase_type', n)), data_prefix='phrase_')
                self.helper.layout = cls.make_layout('Pozycja schematu', components)
            
            @staticmethod
            def get_child_form_prefix(child_form):
                if child_form.model_class == PhraseType:
                    return 'phrase_types__in'
                raise KeyError(type(child_form))
        
        return PositionForm


class LexFormFactory(FormFactory):
    
    field_makers = (
        (
            'lex_type',
            lambda: PhraseTypeFilter(lex=True, help_text='Typ składniowy frazeologizmu.')
        ),
    )

    @classmethod
    def make_form_class(cls, n):

        class LexForm(QueryForm):

            def __init__(self, *args, **kwargs):
                super().__init__(*args, **kwargs)
                self.helper.attrs = cls.make_helper_attrs('lex', n)
                self.model_class = PhraseType
                
                components = and_or_form_creator('Typ frazeologizmu', field_name=cls.unique_name('lex_type', n), data_prefix='phrase_lex')
                self.helper.layout = cls.make_layout('Frazeologizm', components)
        
        return LexForm

class FrameFormFactory(FormFactory):
    
    field_makers = (
        (
            'opinion',
            lambda: ModelMultipleChoiceFilter(
                label='Opinia',
                queryset=FrameOpinion.objects.exclude(key='unk'),
                key='key',
                human_values=polish_strings.FRAME_OPINION,
                lookup='opinion',
            )
        ),
        #(
        #    'operator_opinion',
        #    lambda: OperatorField()
        #),
        (
            'num_arguments',
            lambda: RangeFilter(
                label='Liczba argumentów',
                lookup='arguments_count',
            )
        ),
        (
            'num_preferences',
            lambda: RangeFilter(
                label='Liczba preferencyj selekcyjnych argumentu',
                lookup='argument__preferences_count',
            )
        ),
        # TODO move this to the entry form
        #filter_frame_ = SwitchField('Filtruj ramy')
    )
    
    @classmethod
    def make_form_class(cls, n):
    
        class FrameForm(QueryForm):

            def __init__(self, *args, **kwargs):
                super().__init__(*args, **kwargs)
                self.helper.attrs = cls.make_helper_attrs('frame', n)
                self.model_class = Frame
                
                components = [
                    self.make_field(cls.unique_name('opinion', n)),
                    #self.make_field(cls.unique_name('operator_opinion', n)),
                    self.make_field(cls.unique_name('num_arguments', n)),
                    self.make_field(cls.unique_name('num_preferences', n)),
                ] + \
                    and_or_form_creator('Argument', data_add='argument')
                self.helper.layout = cls.make_layout('Rama semantyczna', components)
        
        return FrameForm


class ArgumentFormFactory(FormFactory):
    
    field_makers = (
        (
            'role',
            lambda: ArgumentFilter(),
        ),
        (
            'preference_type',
            lambda: forms.ChoiceField(
                label='Preferencja selekcyjna',
                choices=(('predefined', 'Predefinowana grupa znaczeń'), ('relational', 'Wyrażona przez relację'), ('synset', 'Wyrażona przez jednostkę leksykalną Słowosieci')),
                required=False,
            )
        ),
        (
            'phrase_type',
            lambda: PhraseTypeFilter(help_text='Typ frazy, przez którą może być realizowany argument.')
        ),
    )
    
    @classmethod
    def make_form_class(cls, n):

        class ArgumentForm(QueryForm):

            def __init__(self, *args, **kwargs):
                super().__init__(*args, **kwargs)
                self.helper.attrs = cls.make_helper_attrs('argument', n)
                self.model_class = Argument
                
                components = [
                    self.make_field(cls.unique_name('role', n)),
                ] + \
                    and_or_form_creator('Preferencja selekcyjna', field_name=cls.unique_name('preference_type', n)) + \
                    and_or_form_creator('Pozycja', data_add='position') + \
                    and_or_form_creator('Fraza', field_name=cls.unique_name('phrase_type', n), data_prefix='phrase_')
                self.helper.layout = cls.make_layout('Argument ramy', components)
        
        return ArgumentForm


class PredefinedPreferenceFormFactory(FormFactory):
    
    field_makers = (
        (
            'predefined',
            lambda: PredefinedPreferenceFilter()
        ),
    )
    
    @classmethod
    def make_form_class(cls, n):

        class PredefinedPreferenceForm(QueryForm):

            def __init__(self, *args, **kwargs):
                super().__init__(*args, **kwargs)
                self.helper.attrs = cls.make_helper_attrs('predefined', n)
                self.model_class = PredefinedSelectionalPreference
                
                components = [
                    self.make_field(cls.unique_name('predefined', n)),
                ]
                self.helper.layout = cls.make_layout('Preferencja predefiniowana', components)
        
        return PredefinedPreferenceForm
            

class RelationalPreferenceFormFactory(FormFactory):
    
    field_makers = (
        (
            'relational',
            lambda: RelationalPreferenceFilter()
        ),
    )
    
    @classmethod
    def make_form_class(cls, n):

        class RelationalPreferenceForm(QueryForm):

            def __init__(self, *args, **kwargs):
                super().__init__(*args, **kwargs)
                self.helper.attrs = cls.make_helper_attrs('relational', n)
                self.model_class = RelationalSelectionalPreference
                
                components = [
                    self.make_field(cls.unique_name('relational', n)),
                ]
                self.helper.layout = cls.make_layout('Preferencja – relacja', components)
        
        return RelationalPreferenceForm
            

class SynsetPreferenceFormFactory(FormFactory):
    
    field_makers = (
        (
            'synset',
            #lambda: SynsetPreferenceFilter()
            lambda: RegexFilter(
                label='Jednostka leksykalna',
                max_length=200,
                lookup='lexical_units__text_rep',
                autocomplete='lu'
            )
        ),
    )
    
    @classmethod
    def make_form_class(cls, n):

        class SynsetPreferenceForm(QueryForm):

            def __init__(self, *args, **kwargs):
                super().__init__(*args, **kwargs)
                self.helper.attrs = cls.make_helper_attrs('synset', n)
                # TODO
                self.model_class = Synset
                
                components = [
                    self.make_field(cls.unique_name('synset', n)),
                ]
                self.helper.layout = cls.make_layout('Preferencja – Słowosieć', components)
        
        return SynsetPreferenceForm
    

class PhraseAttributesFormFactory(FormFactory):
    
    # field types are dynamic here
    field_makers = None
    
    qm = SingleValueQueryManager(lookup='main_type__name')

    @classmethod
    def make_form_class(cls, n, model, lex_model, phrase_type):
        fields = list(filter(lambda x: type(x) in (OneToOneField, ForeignKey, CharField, ManyToManyField) and not x.name.endswith('_ptr'), model._meta.get_fields()))
        if lex_model is not None:
            lex_fields = list(filter(lambda x: type(x) in (OneToOneField, ForeignKey, CharField, ManyToManyField) and not x.name.endswith('_ptr'), lex_model._meta.get_fields()))
        else:
            lex_fields = []
        all_fields = [(f, 'phrase_{}'.format(f.name)) for f in fields] + [(f, 'lex_phrase_{}'.format(f.name)) for f in lex_fields]
        
        class AttributesForm(QueryForm):

            def __init__(self, *args, **kwargs):
                super().__init__(*args, **kwargs)
                self.helper.attrs = cls.make_helper_attrs('phrase_{}'.format(phrase_type), n)
                self.helper.form_id = 'phrase-form'
                self.model_class = PhraseType
                
                components = []
                for _, name in all_fields:
                    uniq_name = cls.unique_name(name, n)
                    if name.endswith('_lexes'):
                        flds = and_or_form_creator('Fraza', field_name=uniq_name, data_prefix='phrase_lex')
                    elif name.endswith('_lex'):
                        flds = and_or_form_creator('Fraza', field_name=uniq_name, data_prefix='phrase_lex')
                    elif name.endswith('_phrase'):
                        flds = and_or_form_creator('Fraza', field_name=uniq_name, data_prefix='phrase_')
                    else:
                        flds = [self.make_field(uniq_name)]
                    components += flds
                pt = polish_strings.PHRASE_TYPE[phrase_type]
                header = pt.capitalize() if phrase_type in polish_strings.NO_PHRASE_NAME else 'Fraza {}'.format(pt)
                if lex_model:
                    header += ' (frazeologizm)'
                self.helper.layout = cls.make_layout(
                    header,
                    #'{} {}'.format('Frazeologizm' if lex_model else 'Fraza', polish_strings.PHRASE_TYPE[phrase_type]),
                    components
                )
            
            # add a phrase type query
            def get_queries(self):
                return super().get_queries() + cls.qm.make_queries(phrase_type, None)
        
        
        for field, name in all_fields:
            #print('***', name, field.name, type(field))
            if field.name == 'lexes':
                form_field = PhraseTypeFilter(help_text='Fraza składowa frazeologizmu porównawczego.', lex=True)
            elif field.name == 'lex':
                form_field = PhraseTypeFilter(help_text='Fraza realizująca frazeologizm.')
            elif field.name == 'phrase':
                form_field = PhraseTypeFilter(help_text='Typ składniowy frazeologizmu.')
            elif type(field) == CharField:
                # TODO other autocompletes?
                autocomplete = 'fixed' if field.name == 'text' else None
                form_field = RegexFilter(
                    label=polish_strings.PHRASE_ATTRIBUTE.get(field.name, field.name),
                    lookup='attributes__{}attributes__{}'.format(phrase_type, field.name),
                    max_length=200,
                    autocomplete=autocomplete,
                )
            else:
                queryset_q = Q(('{}{}attributes__isnull'.format('lex' if name.startswith('lex') else '', phrase_type), False))
                form_field = ModelMultipleChoiceFilter(
                    label=polish_strings.PHRASE_ATTRIBUTE.get(field.name, field.name),
                    queryset=type(field.related_model()).objects.filter(queryset_q).distinct(),
                    key='name',
                    lookup='attributes__{}attributes__{}'.format(phrase_type, field.name),
            )
            AttributesForm.base_fields[cls.unique_name(name, n)] = form_field
        
        return AttributesForm

    '''
    @staticmethod
    def PhraseAttributesForm(phrase_type, *args, **kwargs):
        lex = phrase_type.startswith('lex')
        phrase_type = phrase_type[3:] if lex else phrase_type
        if phrase_type in attrs_helpers:
            helper = attrs_helpers[phrase_type]
            cls, lex_cls = helper.attrs_cls, helper.lex_attrs_cls
            if lex:
                assert(lex_cls is not None)
                return PhraseAttributesFormFactory.get_attributes_form(cls, lex_cls, phrase_type, *args, **kwargs)
            else:
                return PhraseAttributesFormFactory.get_attributes_form(cls, None, phrase_type, *args, **kwargs)
        return PhraseAttributesFormFactory.get_attributes_form(EmptyAttributes, None, phrase_type)
    '''
    
    @classmethod    
    def get_form(cls, phrase_type, unique_number=None, *args, **kwargs):
        unique_number = cls.unique_number() if unique_number is None else unique_number
        lex = phrase_type.startswith('lex')
        phrase_type = phrase_type[3:] if lex else phrase_type
        form_class = None
        if phrase_type in attrs_helpers:
            helper = attrs_helpers[phrase_type]
            attrs_cls, lex_attrs_cls = helper.attrs_cls, helper.lex_attrs_cls
            if lex:
                assert(lex_attrs_cls is not None)
                form_class = cls.make_form_class(unique_number, attrs_cls, lex_attrs_cls, phrase_type)
            else:
                form_class = cls.make_form_class(unique_number, attrs_cls, None, phrase_type)
        if form_class is None:
            form_class = cls.make_form_class(unique_number, EmptyAttributes, None, phrase_type)
        return form_class(*args, **kwargs)