forms.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. # -*- coding: utf-8 -*-
  2. from django import forms
  3. from corpus.models import EvidenceLabel
  4. DEFAULT_LABEL = EvidenceLabel._meta.get_field('label').default
  5. class EvidenceForm(forms.ModelForm):
  6. class Meta:
  7. model = EvidenceLabel
  8. fields = ["label"]
  9. widgets = {
  10. 'label': forms.RadioSelect
  11. }
  12. def __init__(self, *args, **kwargs):
  13. instance = kwargs.get('instance', None)
  14. restore_None = False
  15. if instance and instance.label is None:
  16. # When created, EvidenceLabel get None as label.
  17. # For such cases, on forms, we'll suggest the model.default
  18. instance.label = DEFAULT_LABEL
  19. restore_None = True
  20. super().__init__(*args, **kwargs)
  21. if restore_None:
  22. self.instance.label = None
  23. self.fields['label'].label = ''
  24. def has_changed(self, *args, **kwargs):
  25. changed = super().has_changed(*args, **kwargs)
  26. if not changed and self.instance.label == DEFAULT_LABEL:
  27. # On init we "hacked" the instance so the form was created showing our
  28. # desired default value. Because of that, we may not be seeing that change.
  29. if EvidenceLabel.objects.get(pk=self.instance.pk).label is None:
  30. changed = True
  31. return changed
  32. class EvidenceOnDocumentForm(EvidenceForm):
  33. def __init__(self, *args, **kwargs):
  34. super().__init__(*args, **kwargs)
  35. f_lbl = self.fields['label']
  36. f_lbl.widget = forms.HiddenInput()
  37. # "forms" is the name of some Angular context object on the frontend.
  38. f_lbl.widget.attrs['ng-value'] = 'forms["%s"]' % self.prefix
  39. f_lbl.required = False
  40. class EvidenceToolboxForm(EvidenceForm):
  41. def __init__(self, *args, **kwargs):
  42. super().__init__(*args, **kwargs)
  43. f_lbl = self.fields['label']
  44. prev_widget = f_lbl
  45. f_lbl.widget = forms.RadioSelect(choices=prev_widget.choices)
  46. f_lbl.widget.attrs['ng-model'] = 'current_tool'