forms.py 38.1 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
#-*- coding:utf-8 -*-

import datetime

from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import Group, User
from django.db.models import Q
from django.forms import *

from dictionary.models import *
from semantics.models import FrameOpinion
#Frame, Argument_Model, AttrValueSelectionMode, \
#                              AttrValuesSeparator, Atribute_Value, PositionCategory, \
#                              Argument, Atribute_Model, ArgRealOpinion, Frame_Characteristic, \
#                              Frame_Opinion_Value, B_Frame, Old_Frame, NKJP_Source, NKJP_Opinion, \
#                              NKJP_Example, Message, POS, Vocabulary, Old_Frame_Property, \
#                              Lemma_Status, VocabularyFormat                             

class IntegerRangeField(forms.IntegerField):
    def __init__(self, verbose_name=None, name=None, min_value=None, max_value=None, **kwargs):
        self.min_value, self.max_value = min_value, max_value
        forms.IntegerField.__init__(self, verbose_name, name, **kwargs)
    def formfield(self, **kwargs):
        defaults = {'min_value': self.min_value, 'max_value':self.max_value}
        defaults.update(kwargs)
        return super(IntegerRangeField, self).formfield(**defaults)


class AddPositionForm(Form):
  frequent_positions = ChoiceField(choices=[], label=u'Najczęściej wykorzystywane pozycje', required=False)
  filtered_positions = forms.CharField(label=u'Znajdź potrzebną pozycję', required=False)

  def __init__(self, freq_pos, pos_length=30, 
               pos_tag='verb', phraseologic_frame=False, 
               *args, **kwargs):
    super(AddPositionForm, self).__init__(*args, **kwargs)
    self.fields['frequent_positions'].choices = freq_pos
    if pos_tag == 'verb' and not phraseologic_frame:
        self.fields['filtered_positions'].widget = forms.TextInput(attrs={'size': pos_length})
    else:
        self.fields['filtered_positions'].widget = forms.HiddenInput()
        
class AssignPhraseologicFrameForm(Form):
  phraseologic_frame = ModelChoiceField(label=u'Schemat bazowy', 
                                        queryset=Frame.objects.none(), 
                                        required=True)
  entry = forms.CharField(label=u'Hasło', required=True)

  def __init__(self, phraseologic_frame, 
                *args, **kwargs):
    super(AssignPhraseologicFrameForm, self).__init__(*args, **kwargs)
    self.fields['phraseologic_frame'].initial = phraseologic_frame
    self.fields['phraseologic_frame'].widget = forms.HiddenInput()
    
###########################################################
class AddArgumentForm(Form):
  arg_type = ModelChoiceField(queryset=Argument_Model.objects.order_by('priority').all(), 
                              label=u'Typ', 
                              required=True)
  
  def __init__(self, value=None, empty_label=False,
               model_queryset=Argument_Model.objects.order_by('priority').all(),
               lemma_pos=None, label='Typ', *args, **kwargs):
    super(AddArgumentForm, self).__init__(*args, **kwargs)
    self.fields['arg_type'].label = label
    if empty_label:
        self.fields['arg_type'].empty_label = None
    if lemma_pos:
        model_queryset = model_queryset.filter(poss=lemma_pos)
    self.fields['arg_type'].queryset = model_queryset.all()
    self.fields['arg_type'].initial = value

class TextAttrMultiValueWidget(forms.widgets.MultiWidget):
    def __init__(self, 
                  selection_mode_queryset, value_separator_queryset,
                  *args, **kwargs):
        widgets = [forms.widgets.Select(choices=[(sel_mode.id, sel_mode.name) for sel_mode in selection_mode_queryset.all()]),
                   forms.widgets.Select(choices=[(sep.id, sep.symbol) for sep in value_separator_queryset.all()]),
                   forms.widgets.TextInput()]
        super(TextAttrMultiValueWidget, self).__init__(widgets, *args, **kwargs)
     
    def decompress(self, value):
        if value:
            return [value[0], value[1], value[2]]
        else:
            return [None, None, '']

class TextAttrMultiValueField(MultiValueField):

    def __init__(self, *args, **kwargs):
        all_fields = [
            ChoiceField(),
            ChoiceField(),
            forms.CharField()]
        super(TextAttrMultiValueField, self).__init__(all_fields, *args, **kwargs)

    def compress(self, data_list):
        if data_list:
            return [data_list[0], data_list[1], data_list[2]]
        return [None, None, '']
    
class TextAttrMultiValueForm(Form):
  value = TextAttrMultiValueField()
  
  def __init__(self, 
                label='',
                selection_mode_queryset=AttrValueSelectionMode.objects.all(),
                value_separator_queryset=AttrValuesSeparator.objects.all(),
                selection_mode=None,
                value_separator=None,
                lemmas_text='',
                *args, **kwargs):
    super(TextAttrMultiValueForm, self).__init__(*args, **kwargs)
    self.fields['value'].widget = TextAttrMultiValueWidget(selection_mode_queryset=selection_mode_queryset,
                                                                value_separator_queryset=value_separator_queryset)
    self.fields['value'].initial = [selection_mode, value_separator, lemmas_text]
    self.fields['value'].label = label

################################################################################
class ValueAttrMultiValueWidget(forms.widgets.MultiWidget):
    def __init__(self, 
                  selection_mode_queryset, value_separator_queryset, 
                  values_queryset,
                  *args, **kwargs):
        widgets = [forms.widgets.Select(choices=[(sel_mode.id, sel_mode.name) for sel_mode in selection_mode_queryset.all()]),
                   forms.widgets.Select(choices=[(sep.id, sep.symbol) for sep in value_separator_queryset.all()]),
                   forms.widgets.SelectMultiple(choices=[(value.id, value.name) for value in values_queryset.all()])]
        super(ValueAttrMultiValueWidget, self).__init__(widgets, *args, **kwargs)
     
    def decompress(self, value):
        if value:
            return [value[0], value[1], value[2]]
        else:
            return [None, None, []]

class ValueAttrMultiValueField(MultiValueField):

    def __init__(self, *args, **kwargs):
        super(ValueAttrMultiValueField, self).__init__(*args, **kwargs)

    def compress(self, data_list):
        if data_list:
            return [data_list[0], data_list[1], data_list[2]]
        return [None, None, []]
    
class ValueAttrMultiValueForm(Form):
  value = ValueAttrMultiValueField()
  
  def __init__(self, 
                label='',
                selection_mode_queryset=AttrValueSelectionMode.objects.none(),
                value_separator_queryset=AttrValuesSeparator.objects.none(),
                values_queryset=AttributeParameterModel.objects.none(),
                selection_mode=None, 
                value_separator=None, 
                values=[],
                *args, **kwargs):
    super(ValueAttrMultiValueForm, self).__init__(*args, **kwargs)
    self.fields['value'].widget = ValueAttrMultiValueWidget(selection_mode_queryset=selection_mode_queryset,
                                                            value_separator_queryset=value_separator_queryset,
                                                            values_queryset=values_queryset)
    self.fields['value'].initial = [selection_mode, value_separator, values]
    self.fields['value'].label = label

class CreatePositionForm(Form):
    category = ModelChoiceField(queryset=PositionCategory.objects.filter(control=False),
                                label=u'Funkcja', 
                                required=False)
    def __init__(self, category=None, *args, **kwargs):
        super(CreatePositionForm, self).__init__(*args, **kwargs)
        self.fields['category'].initial = category

class PositionsMultiValueWidget(forms.widgets.MultiWidget):
    def __init__(self, 
                  selection_mode_queryset, value_separator_queryset,
                  *args, **kwargs):
        sel_mode_choices = [('', '------')]
        sel_mode_choices.extend([(sel_mode.id, sel_mode.name) for sel_mode in selection_mode_queryset.all()])
        separator_choices = [(sep.id, sep.symbol) for sep in value_separator_queryset.all()]
        widgets = [forms.widgets.Select(choices=sel_mode_choices),
                   forms.widgets.Select(choices=separator_choices)]
        super(PositionsMultiValueWidget, self).__init__(widgets, *args, **kwargs)
     
    def decompress(self, value):
        if value:
            return [value[0], value[1]]
        else:
            return [None, None]

class PositionsMultiValueField(MultiValueField):

    def __init__(self, *args, **kwargs):
        super(PositionsMultiValueField, self).__init__(*args, **kwargs)

    def compress(self, data_list):
        if data_list:
            return [data_list[0], data_list[1]]
        return [None, None]

class PositionsForm(Form):
    value_positions = PositionsMultiValueField()
  
    def __init__(self,  label='',
                selection_mode_queryset=AttrValueSelectionMode.objects.none(),
                value_separator_queryset=AttrValuesSeparator.objects.none(),
                selection_mode=None, 
                value_separator=None,
                *args, **kwargs):
        super(PositionsForm, self).__init__(*args, **kwargs)
        self.fields['value_positions'].widget = PositionsMultiValueWidget(selection_mode_queryset=selection_mode_queryset,
                                                                          value_separator_queryset=value_separator_queryset)
        self.fields['value_positions'].initial = [selection_mode, value_separator]
        self.fields['value_positions'].label = label


class ArgumentsMultiValueWidget(forms.widgets.MultiWidget):
    def __init__(self, 
                  selection_mode_queryset, value_separator_queryset,
                  *args, **kwargs):
        selection_mode_widget = forms.widgets.Select(choices=[(sel_mode.id, sel_mode.name) for sel_mode in selection_mode_queryset.all()])
        separator_widget = forms.widgets.Select(choices=[(sep.id, sep.symbol) for sep in value_separator_queryset.all()])
        if selection_mode_queryset.count() < 2:
            selection_mode_widget.attrs['hidden'] = True
        if value_separator_queryset.count() < 2:
            separator_widget.attrs['hidden'] = True
        widgets = [selection_mode_widget, separator_widget]
        super(ArgumentsMultiValueWidget, self).__init__(widgets, *args, **kwargs)
     
    def decompress(self, value):
        if value:
            return [value[0], value[1]]
        else:
            return [None, None]

class ArgumentsMultiValueField(MultiValueField):

    def __init__(self, *args, **kwargs):
        super(ArgumentsMultiValueField, self).__init__(*args, **kwargs)

    def compress(self, data_list):
        if data_list:
            return [data_list[0], data_list[1]]
        return [None, None]

class ArgumentsForm(Form):
    value_arguments = ArgumentsMultiValueField()
    value_realizations = ModelMultipleChoiceField(queryset=Argument.objects.none(), 
                                                  required=False, label=u'Rozwinięcia typu frazy')
  
    def __init__(self,  label='',
                selection_mode_queryset=AttrValueSelectionMode.objects.none(),
                value_separator_queryset=AttrValuesSeparator.objects.none(),
                selection_mode=None, 
                value_separator=None,
                base_arg=None,
                sel_realizations=[],
                form_type='standard',
                *args, **kwargs):
        super(ArgumentsForm, self).__init__(*args, **kwargs)
        self.fields['value_arguments'].widget = ArgumentsMultiValueWidget(selection_mode_queryset=selection_mode_queryset,
                                                                          value_separator_queryset=value_separator_queryset)
        self.fields['value_arguments'].initial = [selection_mode, value_separator]
        self.fields['value_arguments'].label = label
        phrase_type_extensions = ArgRealization.objects.none()
        if base_arg:
            phrase_type_extensions = base_arg.realizations.filter(type__sym_name='phrase_type')
        if phrase_type_extensions.exists():
            realizations_ids = []
            for realization in phrase_type_extensions.all():
                argument = realization.argument
                argument_model = Argument_Model.objects.get(arg_model_name=argument.type)
                if argument_model.active:
                    realizations_ids.append(argument.id)
            self.fields['value_realizations'].queryset = Argument.objects.filter(id__in=realizations_ids).order_by('text_rep')
            self.fields['value_realizations'].initial = sel_realizations
        else:
            self.fields.pop('value_realizations')
        if 'value_realizations' in self.fields and form_type == 'realization_main_arg':
            self.fields.pop('value_realizations')


class SelectArgumentForm(Form):
  argument = ModelChoiceField(queryset=Argument.objects.none(), 
                              required=True) 
  
  def __init__(self,  label='',
                *args, **kwargs):
    super(SelectArgumentForm, self).__init__(*args, **kwargs)
    self.fields['argument'].label = label    


class ArgumentAttrChoiceForm(Form):
  value = ModelChoiceField(queryset=Atribute_Model.objects.none(), required=False)
  
  def __init__(self, values, label, value=None,
               lemma_pos=None, *args, **kwargs):
    super(ArgumentAttrChoiceForm, self).__init__(*args, **kwargs)
    self.fields['value'].initial = value
    self.fields['value'].label = label
    self.fields['value'].queryset = values
######################################################################    
class ArgPropositionsForm(Form):
  freq_coordinated = forms.TypedChoiceField(choices=[('', '------')], 
                                            label=u'Często koordynujące się typy fraz:', 
                                            required=False)
  
  def __init__(self, freq_coor_choices=None,
               sel_argument=None, 
               *args, **kwargs):
    super(ArgPropositionsForm, self).__init__(*args, **kwargs)
    if freq_coor_choices:
        choices = [('', '---------')]
        self.fields['freq_coordinated'].choices = choices + freq_coor_choices
        if sel_argument:
            self.fields['freq_coordinated'].initial = sel_argument

class ArgRealOpinionForm(Form):
  opinion = ModelChoiceField(queryset=ArgRealOpinion.objects.order_by('priority'), 
                             label=u'Opinia', required=True)
  
  def __init__(self, sel_opinion=None, *args, **kwargs):
    super(ArgRealOpinionForm, self).__init__(*args, **kwargs)
    self.fields['opinion'].initial = sel_opinion

class AttributeChoiceMultiValueField(MultiValueField):

    def __init__(self, *args, **kwargs):
        super(AttributeChoiceMultiValueField, self).__init__(*args, **kwargs)

    def compress(self, data_list):
        if data_list:
            return [data_list[0], data_list[1]]
        return [None, []]
    
class AttributeChoiceMultiValueWidget(forms.widgets.MultiWidget):
    def __init__(self, 
                  parameter_type_queryset, subparameters_queryset,
                  *args, **kwargs):
        widgets = []
        parameter_model_choices = [('', '---------')]
        parameter_model_choices.extend([(param_type.id, param_type.name) for param_type in parameter_type_queryset.all()])
        parameter_type_widget = forms.widgets.Select(choices=parameter_model_choices)
        widgets.append(parameter_type_widget)
        if subparameters_queryset.exists():
            subparameters_widget = forms.widgets.SelectMultiple(choices=[(subparam.id, subparam.name) for subparam in subparameters_queryset.all()])
            widgets.append(subparameters_widget)
        super(AttributeChoiceMultiValueWidget, self).__init__(widgets, *args, **kwargs)
     
    def decompress(self, value):
        if value:
            return [value[0], value[1]]
        else:
            return [None, []]
    
class AtributeChoiceForm(Form):
  value_parameter = AttributeChoiceMultiValueField()
  
  def __init__(self, values, label='', value=None, 
                subparameters=AttributeSubparameter.objects.none(),
                sel_subparameters=[],#show_related=False, 
                lemma_pos=None, *args, **kwargs):
    super(AtributeChoiceForm, self).__init__(*args, **kwargs)
    # czy pokazywac wartosci mogace wystepowac jedynie jako w realizacjach argumentow () 
    # @TODO zmienic nazwe flagi show_related bo mylaca
    values = values.exclude(related=True)
    if lemma_pos:
        values = values.filter(poss=lemma_pos)
    self.fields['value_parameter'].widget = AttributeChoiceMultiValueWidget(parameter_type_queryset=values,
                                                                            subparameters_queryset=subparameters)
    self.fields['value_parameter'].initial = [value, sel_subparameters]
    self.fields['value_parameter'].label = label
    
class AtributeTextForm(Form):
  value = forms.CharField()

  def __init__(self, label, value = None,
                *args, **kwargs):
    super(AtributeTextForm, self).__init__(*args, **kwargs)
    self.fields['value'].label = label
    self.fields['value'].initial = value
    
class FrameForm(Form):
  aspect = ModelChoiceField(label=u'*Aspekt', queryset=Frame_Characteristic.objects.none(), 
                            required=False)
  reflex = ModelChoiceField(label=u'*Zwrotność', queryset=Frame_Characteristic.objects.none(), 
                            required=False)
  negativity = ModelChoiceField(label=u'*Negatywność', queryset=Frame_Characteristic.objects.none(), 
                                required=False)
  predicativity = ModelChoiceField(label=u'*Predykatywność', queryset=Frame_Characteristic.objects.none(), 
                                   required=False)
  frame_opinion = ModelChoiceField(label=u'*Ocena schematu', 
                                   queryset=Frame_Opinion_Value.objects.order_by('priority'), 
                                   required=False)
  base_frame = ModelChoiceField(label=u'Schemat bazowy', 
                                queryset=Frame.objects.filter(base=True), 
                                required=False)
  propose_B = ModelChoiceField(label=u'Proponowane schematy [inne]', queryset=B_Frame.objects.none(), 
                               required=False)
  propose_skladnica = ModelChoiceField(label=u'Proponowane schematy [Składnica]', queryset=Old_Frame.objects.none(), 
                             required=False)
  propose_phraseology = ModelChoiceField(label=u'*Proponowane schematy [frazeologia]', queryset=Frame.objects.none(), 
                                         required=False)
  
  def __init__(self, aspect_values, reflex_values, neg_values, pred_values, 
               proposed_frames_skladnica, proposed_frames_B,
               proposed_phraseology_frames, pos,
               aspect_val=None, reflex_val=None, neg_val=None, pred_val=None,
               frame_opinion_val=None, edit=False, phraseologic_modification=False,
               *args, **kwargs):
    super(FrameForm, self).__init__(*args, **kwargs)
    self.fields['aspect'].queryset = aspect_values
    self.fields['aspect'].initial = aspect_val
    self.fields['reflex'].queryset = reflex_values
    self.fields['reflex'].initial = reflex_val
    self.fields['negativity'].queryset = neg_values
    self.fields['negativity'].initial = neg_val
    self.fields['predicativity'].queryset = pred_values
    self.fields['predicativity'].initial = pred_val
    self.fields['frame_opinion'].initial = frame_opinion_val
    if proposed_frames_skladnica:
        self.fields['propose_skladnica'].queryset = proposed_frames_skladnica.order_by('old_frame_value')
    else:
        self.fields['propose_skladnica'].widget = forms.HiddenInput()
    if proposed_frames_B and proposed_frames_B.count() > 0:
        self.fields['propose_B'].queryset = proposed_frames_B.order_by('text_id')
    else:
        self.fields['propose_B'].widget = forms.HiddenInput()
    if edit or pos.tag != 'verb' or phraseologic_modification:
        self.fields['base_frame'].widget = forms.HiddenInput()
    
    self.fields['propose_phraseology'].queryset = proposed_phraseology_frames
    if not phraseologic_modification or not proposed_phraseology_frames.exists():
        self.fields['propose_phraseology'].widget = forms.HiddenInput()
        self.fields['propose_phraseology'].widget.attrs['disabled'] = 'disabled'
        
class FrameConversionForm(Form):
  frame_versions = ModelChoiceField(label=u'Wersja schematu',
                                    queryset=Frame.objects.none(), 
                                    required=True)
  
  def __init__(self, frame_versions, *args, **kwargs):
    super(FrameConversionForm, self).__init__(*args, **kwargs)
    self.fields['frame_versions'].queryset = frame_versions
        
class FrameAspectForm(Form):
  aspect = ModelChoiceField(label='', queryset=Frame_Characteristic.objects.filter(type=u'ASPEKT'), 
                            required=True)
  
  def __init__(self, aspect_val=Frame_Characteristic.objects.filter(type=u'ASPEKT', value__value='_'), 
               *args, **kwargs):
    super(FrameAspectForm, self).__init__(*args, **kwargs)
    self.fields['aspect'].initial = aspect_val

class FrameOpinionForm(Form):
    opinion = ModelChoiceField(label='', queryset=Frame_Opinion_Value.objects.order_by('priority'), 
                               required=True)
  
    def __init__(self, opinion_val=Frame_Opinion_Value.objects.order_by('priority')[0], 
                 *args, **kwargs):
        super(FrameOpinionForm, self).__init__(*args, **kwargs)
        self.fields['opinion'].initial = opinion_val 
          
    
class Pos_Cat_Form(Form):
  category = ModelChoiceField(label=u'Funkcja', queryset=PositionCategory.objects.none(), required=False)
  control = ModelMultipleChoiceField(label=u'Kontrola', queryset=PositionCategory.objects.none(), required=False)
  
  def __init__(self, part_of_speech, category_val=None, control_val=None, *args, **kwargs):
    super(Pos_Cat_Form, self).__init__(*args, **kwargs)
    self.fields['category'].queryset = PositionCategory.objects.filter(poss=part_of_speech,
                                                                       control=False).order_by('priority')
    self.fields['control'].queryset = PositionCategory.objects.filter(poss=part_of_speech,
                                                                      control=True).order_by('priority')
    self.fields['category'].initial = category_val
    self.fields['control'].initial = control_val


class AddNkjpExampleForm(ModelForm):
  sentence = forms.CharField(label=u'Przykładowe zdanie', widget = Textarea(attrs={'cols': 80, 'rows': 1}))
  source = ModelChoiceField(label=u'Źródło', queryset=NKJP_Source.objects.all())
  opinion = ModelChoiceField(label=u'Ocena doboru', queryset=NKJP_Opinion.objects.all())
  comment = forms.CharField(label=u'Dodatkowy komentarz', widget = Textarea(attrs={'cols': 80, 'rows': 1})) 

  class Meta:
    model = NKJP_Example
    exclude = ('frame', 'arguments', 'approvers', 'approved', 'semantic',)
   
    
class ExampleOpinionForm(Form):
  is_wrong = forms.BooleanField(label=u'Niepoprawny przykład', required=False, initial=False)
  
  def __init__(self, is_wrong=False, 
               *args, **kwargs):
    super(ExampleOpinionForm, self).__init__(*args, **kwargs)
    self.fields['is_wrong'].initial = is_wrong


class MessageForm(ModelForm):
  private = forms.BooleanField(label=u'Prywatna', required=False, initial=False)
  topic = forms.CharField(label=u'Temat', widget = Textarea(attrs={'cols': 80, 'rows': 1}))
  message_text = forms.CharField(label=u'Treść', widget = Textarea(attrs={'cols': 80, 'rows': 20})) 
  
  def __init__(self, hide_private=False, topic='', *args, **kwargs):
    super(MessageForm, self).__init__(*args, **kwargs)
    if hide_private:
      self.fields['private'].widget = forms.HiddenInput()
      self.fields['private'].initial = False
      self.fields['topic'].initial = topic

  class Meta:
    model = Message
    exclude = ('sender', 'lemma', 'new', 'recipient')


############################ sorting, filtering
 
class FilterForm(Form):
  # Lemma filters
  lemma = forms.CharField(label=u'Lemat', required=False)
  pos = ModelChoiceField(label=u'Część mowy', queryset=POS.objects.none(), required=False)
  contains_phraseology = ChoiceField(choices=[('', '---------'), ('yes', 'zawiera'), ('no', 'nie zawiera')], 
                                     label=u'Frazeologia', required=False)
  owner = ModelChoiceField(label=u'Właściciel', queryset=User.objects.none(), required=False)
  phraseologist = ModelChoiceField(label=u'Frazeolog', queryset=User.objects.none(), required=False)
  semanticist = ModelChoiceField(label=u'Semantyk', queryset=User.objects.none(), required=False)
  vocabulary = ModelChoiceField(label=u'Słownik', queryset=Vocabulary.objects.none(), required=False)
  status = ModelChoiceField(label=u'Status', queryset=Lemma_Status.objects.none(), required=False)
  has_message_from = ModelChoiceField(label=u'Zawiera wiadomość od', queryset=User.objects.none(), 
                                      required=False)
  example_source = ModelChoiceField(label=u'Zawiera przykład', queryset=NKJP_Source.objects.filter(confirmation_required=True), 
                                         required=False)
  approver = ModelChoiceField(label=u'Zatwierdzający przykład', queryset=User.objects.filter(Q(groups__permissions__codename='confirm_example') | 
                                                                                             Q(is_superuser=True)).distinct().order_by('username'), 
                                         required=False)
  # Schema filters
  schema_type = ChoiceField(choices=[('', '---------'), ('normal', 'normalny'), ('phraseologic', 'frazeologiczny')], 
                            label=u'Typ schematu', required=False)
  reflex = ModelChoiceField(label=u'Zwrotność',
                            queryset=Frame_Characteristic.objects.filter(type=u'ZWROTNOŚĆ').order_by('value__priority'), 
                            required=False)
  negativity = ModelChoiceField(label=u'Negatywność', 
                                queryset=Frame_Characteristic.objects.filter(type=u'NEGATYWNOŚĆ').order_by('value__priority'), 
                                required=False)
  predicativity = ModelChoiceField(label=u'Predykatywność', 
                                   queryset=Frame_Characteristic.objects.filter(type=u'PREDYKATYWNOŚĆ').order_by('value__priority'), 
                                   required=False)
  aspect = ModelChoiceField(label=u'Aspekt', 
                            queryset=Frame_Characteristic.objects.filter(type=u'ASPEKT').order_by('value__priority'), 
                            required=False)
  has_argument = forms.CharField(label=u'Zawiera typ frazy', required=False)
  has_position = forms.CharField(label=u'Zawiera pozycję', required=False) 
  schema_opinion = ModelChoiceField(label=u'Opinia o schemacie', queryset=Frame_Opinion_Value.objects.all(), 
                                    required=False)
  filter_frames = forms.BooleanField(label=u'Odfiltruj niepasujące schematy', initial=False,
                                     required=False)
  # Frame filters
  frame_opinion = ModelChoiceField(label=u'Opinia o ramie', queryset=FrameOpinion.objects.order_by('priority'), 
                                   required=False)
  
  def __init__(self, users, phraseologists, semanticists, vocabularies, statuses, senders,
               lemma='.*', sel_pos=None, contains_phraseology=None, 
               sel_user=None, sel_phraseologist=None, sel_semanticist=None,
               sel_vocabulary=None, sel_status=None, sel_schema_type=None,
               sel_reflex=None, sel_negativity=None, sel_predicativity=None, 
               sel_aspect=None, sel_has_argument='.*', sel_has_position='.*',
               sel_schema_opinion=None, can_confirm_example=False, sel_example_source=None, 
               sel_approver=None, sel_sender=None, 
               sel_frame_opinion=None, *args, **kwargs):
    super(FilterForm, self).__init__(*args, **kwargs)
    
    self.fields['pos'].queryset = POS.objects.exclude(tag='unk')
    self.fields['owner'].queryset = users
    self.fields['phraseologist'].queryset = phraseologists
    self.fields['semanticist'].queryset = semanticists
    self.fields['vocabulary'].queryset = vocabularies
    self.fields['status'].queryset = statuses
    self.fields['lemma'].initial = lemma
    self.fields['pos'].initial = sel_pos
    self.fields['contains_phraseology'].initial = contains_phraseology
    self.fields['owner'].initial = sel_user
    self.fields['phraseologist'].initial = sel_phraseologist
    self.fields['semanticist'].initial = sel_semanticist
    self.fields['vocabulary'].initial = sel_vocabulary
    self.fields['status'].initial = sel_status
    if can_confirm_example:
      self.fields['example_source'].initial = sel_example_source
      self.fields['approver'].initial = sel_approver
    else:
      self.fields['example_source'].widget = self.fields['example_source'].hidden_widget()
      self.fields['example_source'].initial = None
      self.fields['approver'].widget = self.fields['approver'].hidden_widget()
      self.fields['approver'].initial = None
    self.fields['reflex'].initial = sel_reflex
    self.fields['negativity'].initial = sel_negativity
    self.fields['predicativity'].initial = sel_predicativity
    self.fields['aspect'].initial = sel_aspect
    self.fields['has_argument'].initial = sel_has_argument
    self.fields['has_position'].initial = sel_has_position
    self.fields['schema_opinion'].initial = sel_schema_opinion
    self.fields['has_message_from'].initial = sel_sender
    self.fields['has_message_from'].queryset = senders
    
    self.fields['schema_type'].initial = sel_schema_type
    self.fields['frame_opinion'].initial = sel_frame_opinion

    self.hide_unused_fields()
    
  def hide_unused_fields(self):
    for field_name in self.fields:
      if hasattr(self.fields[field_name], 'queryset') and not self.fields[field_name].queryset.exists():
        self.fields[field_name].widget = forms.HiddenInput()
        
    
class SortForm(Form):
  id_priority = forms.IntegerField(label=u'Identyfikator', required=False, 
                                   widget=forms.TextInput(attrs={'size':'2'}))
  id_sort_order = ChoiceField(choices=[], label=u'', required=False)
  entry_priority = forms.IntegerField(label=u'Hasło', required=False, 
                                      widget=forms.TextInput(attrs={'size':'2'}))
  entry_sort_order = ChoiceField(choices=[], label=u'', required=False)
  owner_priority = forms.IntegerField(label=u'Właściciel', required=False, 
                                      widget=forms.TextInput(attrs={'size':'2'}))
  owner_sort_order = ChoiceField(choices=[], label=u'', required=False)
  phraseologist_priority = forms.IntegerField(label=u'Frazeolog', required=False, 
                                              widget=forms.TextInput(attrs={'size':'2'}))
  phraseologist_sort_order = ChoiceField(choices=[], label=u'', required=False)
  semanticist_priority = forms.IntegerField(label=u'Semantyk', required=False, 
                                      widget=forms.TextInput(attrs={'size':'2'}))
  semanticist_sort_order = ChoiceField(choices=[], label=u'', required=False)
  vocabulary_priority = forms.IntegerField(label=u'Słownik', required=False, 
                                           widget=forms.TextInput(attrs={'size':'2'}))
  vocabulary_sort_order = ChoiceField(choices=[], label=u'', required=False)  
  status_priority = forms.IntegerField(label=u'Status', required=False, 
                                       widget=forms.TextInput(attrs={'size':'2'}))
  status_sort_order = ChoiceField(choices=[], label=u'', required=False)
    
    
  def __init__(self,  
          id_order_choice=None, id_priority_choice=None, 
          entry_order_choice=None, entry_priority_choice=None,
          owner_order_choice=None, owner_priority_choice=None,
          phraseologist_order_choice=None, phraseologist_priority_choice=None,
          semanticist_order_choice=None, semanticist_priority_choice=None,
          vocabulary_order_choice=None, vocabulary_priority_choice=None,
          status_order_choice=None, status_priority_choice=None,
           *args, **kwargs):
    super(SortForm, self).__init__(*args, **kwargs)
          
    order_choices = [(None, u'--------')]
    order_choices.append((u'desc', u'malejąco'))
    order_choices.append((u'asc', u'rosnąco'))
    
    self.fields['id_sort_order'].choices = order_choices
    self.fields['entry_sort_order'].choices = order_choices
    self.fields['owner_sort_order'].choices = order_choices
    self.fields['phraseologist_sort_order'].choices = order_choices
    self.fields['semanticist_sort_order'].choices = order_choices
    self.fields['vocabulary_sort_order'].choices = order_choices
    self.fields['status_sort_order'].choices = order_choices
    
    self.fields['id_sort_order'].initial = id_order_choice
    self.fields['entry_sort_order'].initial = entry_order_choice
    self.fields['owner_sort_order'].initial = owner_order_choice
    self.fields['phraseologist_sort_order'].initial = phraseologist_order_choice
    self.fields['semanticist_sort_order'].initial = semanticist_order_choice
    self.fields['vocabulary_sort_order'].initial = vocabulary_order_choice
    self.fields['status_sort_order'].initial = status_order_choice
    
    self.fields['id_priority'].initial = id_priority_choice
    self.fields['entry_priority'].initial = entry_priority_choice
    self.fields['owner_priority'].initial = owner_priority_choice
    self.fields['phraseologist_priority'].initial = phraseologist_priority_choice
    self.fields['semanticist_priority'].initial = semanticist_priority_choice
    self.fields['vocabulary_priority'].initial = vocabulary_priority_choice
    self.fields['status_priority'].initial = status_priority_choice


####################### CZASOWNIKI PODOBNE ##########################################3
class SimilarLemmasNewForm(Form):
  status = ModelChoiceField(label=u'Minimalny status', queryset=Lemma_Status.objects.none(), required=False)
  compatibility = IntegerRangeField(label=u'Skala podobieństwa [%]', required=True, 
                                          min_value=1, max_value=100,
                                          widget=forms.TextInput(attrs={'size':'3'})) 
  
  def __init__(self, statuses, compatibility=50, *args, **kwargs):
    super(SimilarLemmasNewForm, self).__init__(*args, **kwargs)
    self.fields['status'].queryset = statuses
    
class SimilarLemmasOldForm(Form):
  compatibility = IntegerRangeField(label=u'Skala podobieństwa [%]', required=True, 
                                    min_value=1, max_value=100,
                                    widget=forms.TextInput(attrs={'size':'3'}))
  
  def __init__(self, compatibility=50, *args, **kwargs):
    super(SimilarLemmasOldForm, self).__init__(*args, **kwargs)
    
    
##################### Słowniki ######################################
class GetVocabularyForm(Form):
  vocabulary = ModelMultipleChoiceField(label=u'Słownik', queryset=Vocabulary.objects.all())
  pos = ModelMultipleChoiceField(label=u'Część mowy', queryset=POS.objects.exclude(tag=u'unk').order_by('priority'))
  format = ModelChoiceField(label=u'Format wyjściowy', queryset=VocabularyFormat.objects.all())
  frame_opinion = ModelMultipleChoiceField(label=u'Rodzaje schematów', queryset=Frame_Opinion_Value.objects.all())
  lemma_status = ModelMultipleChoiceField(label=u'Statusy haseł', queryset=Lemma_Status.objects.all())
  owner = ModelMultipleChoiceField(label=u'Właściciele', 
                                  queryset=User.objects.filter(lemmas__old=False).distinct().order_by('username'))
  addframeopinion = forms.BooleanField(label=u'Dodaj opinie do formatu tekstowego', required=False, initial=False)

class ManageVocabPermForm(ModelForm):
  editors = ModelMultipleChoiceField(label=u'Edytorzy', queryset = User.objects.order_by('username'))
  viewers = ModelMultipleChoiceField(label=u'Obserwatorzy', queryset = User.objects.order_by('username'))
  
  class Meta:
    model = Vocabulary
    exclude = ('name', )
  
  def __init__(self, editors, viewers, *args, **kwargs):
    super(ManageVocabPermForm, self).__init__(*args, **kwargs)
    self.fields['editors'].initial = [c.pk for c in editors.all()]
    self.fields['viewers'].initial = [c.pk for c in viewers.all()]     
    
#################### Zarzadzanie uzytkownikami ###################################
class UserCreateForm(UserCreationForm):
    group = ModelChoiceField(label=u'Funkcja', queryset=Group.objects.order_by('group_settings__priority'), 
                              required=True)
 
    class Meta:
        model = User
        fields = ("username", 'email', "password1", "password2")
 
        
class ChangeUserFunctionForm(Form):
    user = ModelChoiceField(label=u'Użytkownik', queryset=User.objects.order_by('username'), 
                              required=True)
    group = ModelChoiceField(label=u'Funkcja', queryset=Group.objects.order_by('group_settings__priority'), 
                              required=True)
    
    def __init__(self, user_id=-1, *args, **kwargs):
      super(ChangeUserFunctionForm, self).__init__(*args, **kwargs)
      if user_id >=0:
        user = User.objects.get(id=user_id)
        self.fields['user'].initial = user
        if not user.is_superuser:
          self.fields['group'].initial = user.groups.all()[0]
   
          
class PropFramesForm(Form):
    start = forms.DateField(initial=datetime.date.today)
    end = forms.DateField(initial=datetime.date.today)


#################### Statystyki argumentow ###################################
class ArgStatsForm(Form):
    arguments = ModelMultipleChoiceField(label=u'Realizacje', queryset = Argument.objects.order_by('text_rep'))
    arg_types = ModelChoiceField(label=u'Typ realizacji', queryset = Argument_Model.objects.order_by('priority'))
    bucket_size = IntegerRangeField(label=u'Wielkość kubełka', required=True, 
                                    min_value=1)
  
    def __init__(self, *args, **kwargs):
        super(ArgStatsForm, self).__init__(*args, **kwargs)
        self.fields['bucket_size'].initial = 50