forms.py
27.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
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, LemmaOperator, LemmaCooccur, Lemma
from semantics.models import (
Frame, FrameOpinion,
Argument, SemanticRole, RoleAttribute,
PredefinedSelectionalPreference, RelationalSelectionalPreference, SelectionalPreferenceRelation,
)
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,
)
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
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):
print(type(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('filter') and not key.startswith('negate'):
form_field = self.fields[key]
conjunction = form_field.query_manager.default_conjunction
queries += form_field.query_manager.make_queries(value, conjunction)
return queries
def is_negated(self):
for key, value in self.cleaned_data.items():
if key.startswith('negate') and value:
return True
return False
@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" data-formtype="{}">'.format(data_add)),
add_button,
or_button(button_label),
layout.HTML('</div>'),
]
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):
form_class_name = None
form_model = None
form_formtype = None
form_header = None
@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(
'{} <span class="collapsed-info"></span> <button class="btn collapse-button btn-sm btn-secondary" data-collapsed="false" type="button">zwiń</button><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
assert(cls.form_class_name is not None)
assert(cls.form_model is not None)
assert(cls.form_formtype is not None)
assert(cls.form_header is not None)
def form_init(self, *args, **kwargs):
super(type(self), self).__init__(*args, **kwargs)
self.helper.attrs = cls.make_helper_attrs(cls.form_formtype, unique_number)
self.model_class = cls.form_model
components = [self.make_field(cls.unique_name('negated', unique_number))]
for field_name, field_maker, component_maker in cls.field_makers:
if component_maker:
component = component_maker(unique_number)
else:
component = self.make_field(cls.unique_name(field_name, unique_number))
if type(component) == list:
components += component
else:
components.append(component)
self.helper.layout = cls.make_layout(cls.form_header, components)
form_class = type(cls.form_class_name, (QueryForm,), {
'__init__' : form_init,
'get_child_form_prefix' : lambda self, child_form: cls.get_child_form_prefix(child_form),
})
form_class.base_fields[cls.unique_name('negated', unique_number)] = SwitchField('Zaneguj', css_class='negate-switch')
for field_name, field_maker, layout_maker in cls.field_makers:
if field_name is not None:
form_class.base_fields[FormFactory.unique_name(field_name, unique_number)] = field_maker()
return form_class(*args, **kwargs)
@staticmethod
def get_child_form_prefix():
raise NotImplementedError
class SchemaFormFactory(FormFactory):
form_class_name = 'SchemaForm'
form_model = Schema
form_formtype = 'schema'
form_header = 'Schemat składniowy'
field_makers = (
(
'opinion',
lambda: ModelMultipleChoiceFilter(
label='Opinia o schemacie',
queryset=SchemaOpinion.objects.filter(schemata__isnull=False).distinct(),
key='key',
human_values=polish_strings.SCHEMA_OPINION,
lookup='opinion',
#initial=SchemaOpinion.objects.filter(key__in=('col', 'vul')),
),
None,
),
(
'type',
lambda: MultipleChoiceFilter(
label='Typ',
choices=((False, 'zwykły'), (True, 'frazeologiczny'),),
lookup='phraseologic',
),
None,
),
(
'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',
),
None,
),
#(
# '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,
# )
#),
#(
# '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,
# )
#),
#(
# '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,
# )
#),
#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',
# )
#),
(
None, None,
lambda n: and_or_form_creator('Pozycja', data_add='position'),
),
)
@staticmethod
def get_child_form_prefix(child_form):
if child_form.model_class == Position:
return 'positions__in'
raise KeyError(type(child_form))
class PositionFormFactory(FormFactory):
form_class_name = 'PositionForm'
form_model = Position
form_formtype = 'position'
form_header = 'Pozycja schematu'
field_makers = (
(
'gram_function',
lambda: ModelMultipleChoiceFilter(
label='Funkcja gramatyczna',
queryset=SyntacticFunction.objects.all(),
key='name',
human_values=polish_strings.GRAM_FUNCTION,
lookup='function',
), None,
),
(
'control',
lambda: ModelMultipleChoiceFilter(
label='Kontrola',
queryset=Control.objects.filter(positions__isnull=False).distinct(),
key='name',
human_values=polish_strings.CONTROL,
lookup='control',
), None,
),
(
'pred_control',
lambda: ModelMultipleChoiceFilter(
label='Kontrola predykatywna',
queryset=PredicativeControl.objects.all(),
key='name',
human_values=polish_strings.CONTROL,
lookup='pred_control',
), None,
),
(
'phrase_type',
lambda: PhraseTypeFilter(help_text='Typ frazy występujący na pozycji.'),
lambda n: and_or_form_creator('Fraza', field_name=(FormFactory.unique_name('phrase_type', n)), data_prefix='phrase_'),
),
)
@staticmethod
def get_child_form_prefix(child_form):
if child_form.model_class == PhraseType:
return 'phrase_types__in'
raise KeyError(type(child_form))
class LexFormFactory(FormFactory):
form_class_name = 'LexForm'
form_model = PhraseType
form_formtype = 'phrase_lex'
form_header = 'Frazeologizm'
field_makers = (
(
'lex_type',
lambda: PhraseTypeFilter(lex=True, help_text='Typ składniowy frazeologizmu.'),
lambda n: and_or_form_creator('Typ frazeologizmu', field_name=FormFactory.unique_name('lex_type', n), data_prefix='phrase_lex')
),
)
@staticmethod
def get_child_form_prefix(child_form):
if child_form.model_class == PhraseType:
return 'id__in'
raise KeyError(type(child_form))
class LemmaFormFactory(FormFactory):
form_class_name = 'LemmaForm'
form_model = Lemma
form_formtype = 'lemma'
form_header = 'Lemat'
field_makers = (
(
'lemma',
lambda: RegexFilter(
label='Lemat',
max_length=32,
lookup='name',
autocomplete='lex_lemma'
), None,
),
)
class FrameFormFactory(FormFactory):
form_class_name = 'FrameForm'
form_model = Frame
form_formtype = 'frame'
form_header = 'Rama semantyczna'
field_makers = (
(
'opinion',
lambda: ModelMultipleChoiceFilter(
label='Opinia',
queryset=FrameOpinion.objects.exclude(key='unk').filter(frame__isnull=False).distinct(),
key='key',
human_values=polish_strings.FRAME_OPINION,
lookup='opinion',
), None,
),
(
'num_arguments',
lambda: RangeFilter(
label='Liczba argumentów',
lookup='arguments_count',
), None
),
(
'num_preferences',
lambda: RangeFilter(
label='Liczba preferencyj selekcyjnych argumentu',
lookup='argument__preferences_count',
), None
),
(
None, None,
lambda n: and_or_form_creator('Argument', data_add='argument'),
),
)
class ArgumentFormFactory(FormFactory):
form_class_name = 'ArgumentForm'
form_model = Argument
form_formtype = 'argument'
form_header = 'Argument ramy'
field_makers = (
(
'role',
lambda: ModelMultipleChoiceFilter(
label='Rola',
queryset=SemanticRole.objects.filter(argumentrole__argument__isnull=False).distinct(),
key='role',
lookup='role__role',
), None,
),
(
'role_attribute',
lambda: ModelMultipleChoiceFilter(
label='Atrybut roli',
queryset=RoleAttribute.objects.filter(argumentrole__argument__isnull=False).distinct(),
key='attribute',
lookup='role__attribute',
), None,
),
(
'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,
),
lambda n: and_or_form_creator('Preferencja selekcyjna', field_name=FormFactory.unique_name('preference_type', n))
),
(
None, None,
lambda n: and_or_form_creator('Pozycja', data_add='position'),
),
(
'phrase_type',
lambda: PhraseTypeFilter(help_text='Typ frazy, przez którą może być realizowany argument.'),
lambda n: and_or_form_creator('Fraza', field_name=FormFactory.unique_name('phrase_type', n), data_prefix='phrase_'),
),
)
class PredefinedPreferenceFormFactory(FormFactory):
form_class_name = 'PredefinedPreferenceForm'
form_model = PredefinedSelectionalPreference
form_formtype = 'predefined'
form_header = 'Preferencja predefiniowana'
field_makers = (
(
'predefined',
lambda: ModelMultipleChoiceFilter(
label='Predefiniowane',
queryset=PredefinedSelectionalPreference.objects.all(),
key='key',
# TODO
lookup='predefined',
), None,
),
)
class RelationalPreferenceFormFactory(FormFactory):
form_class_name = 'RelationalPreferenceForm'
form_model = RelationalSelectionalPreference
form_formtype = 'relational'
form_header = 'Preferencja – relacja'
field_makers = (
(
'relation',
lambda: ModelMultipleChoiceFilter(
label='Relacja',
queryset=SelectionalPreferenceRelation.objects.all(),
key='key',
# TODO
lookup='relation',
), None,
),
(
'to_role',
lambda : ModelMultipleChoiceFilter(
label='Do: rola',
queryset=SemanticRole.objects.all(),
key='role',
lookup='to__role__role',
), None,
),
(
'to_attribute',
lambda: ModelMultipleChoiceFilter(
label='Do: atrybut',
queryset=RoleAttribute.objects.all(),
key='attribute',
lookup='to__role__attribute',
), None,
)
)
class SynsetPreferenceFormFactory(FormFactory):
form_class_name = 'SynsetPreferenceForm'
# TODO
form_model = Synset
form_formtype = 'synset'
form_header = 'Preferencja – Słowosieć'
field_makers = (
(
'synset',
lambda: RegexFilter(
label='Jednostka leksykalna',
max_length=200,
lookup='lexical_units__text_rep',
autocomplete='lu'
), None,
),
)
class PhraseAttributesFormFactory(FormFactory):
# field types are dynamic here
field_makers = None
@classmethod
def make_form_class(cls, n, model, lex_model, phrase_type):
print('*****************', n, model, lex_model, phrase_type)
lex_phrase = lex_model is not None
fields = list(filter(lambda x: type(x) in (OneToOneField, ForeignKey, CharField, ManyToManyField) and not x.name.endswith('_ptr'), model._meta.get_fields()))
if lex_phrase:
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, '{}'.format(f.name)) for f in fields] + [(f, 'lex_{}'.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('lex' if lex_model else '', phrase_type), n)
self.helper.form_id = 'phrase-form'
self.model_class = PhraseType
components = [self.make_field(cls.unique_name('negated', n))]
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
if lex_model:
components += [
self.make_field(cls.unique_name('lex_lemma_operator', n)),
self.make_field(cls.unique_name('lex_lemma_cooccur', n)),
] + and_or_form_creator('Lemat', data_add='lemma')
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,
components
)
# add a phrase type query
def get_queries(self):
pt_q = Q(('{}main_type__name'.format('lexicalized_phrase__' if lex_phrase else ''), phrase_type))
return super().get_queries() + [pt_q]
@staticmethod
def get_child_form_prefix(child_form):
if child_form.model_class == Lemma:
return 'lemmata__in'
raise KeyError(type(child_form))
AttributesForm.base_fields[cls.unique_name('negated', n)] = SwitchField('Zaneguj', css_class='negate-switch')
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:
lex_attr = name.startswith('lex')
queryset_q = Q(('{}{}attributes__isnull'.format('lex' if lex_attr 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',
human_values=polish_strings.PHRASE_ATTRIBUTE_VALUE,
lookup='{}attributes__{}{}attributes__{}'.format(
'lexicalized_phrase__' if lex_phrase and not lex_attr else '',
'lexphrasetypeattributes__lex' if lex_attr else '',
phrase_type,
field.name,
),
)
AttributesForm.base_fields[cls.unique_name(name, n)] = form_field
if lex_model:
AttributesForm.base_fields[cls.unique_name('lex_lemma_operator', n)] = ModelMultipleChoiceFilter(
label='Operator lematów',
queryset=LemmaOperator.objects.all(),
key='name',
lookup='lemma_operator',
)
AttributesForm.base_fields[cls.unique_name('lex_lemma_cooccur', n)] = ModelMultipleChoiceFilter(
label='Łączenie lematów',
queryset=LemmaCooccur.objects.all(),
key='name',
lookup='lemma_cooccur',
)
return AttributesForm
@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)