Django Library PyGal
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

forms.py 2.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. from django import forms
  2. from .models import Tag, is_valid_area
  3. class TagForm(forms.ModelForm):
  4. COORD_KEYS = ['topleft_x', 'topleft_y', 'bottomright_x', 'bottomright_y']
  5. class Meta:
  6. model = Tag
  7. fields = ['text', 'topleft_x', 'topleft_y', 'bottomright_x', 'bottomright_y']
  8. widgets = {
  9. 'topleft_x': forms.HiddenInput(),
  10. 'topleft_y': forms.HiddenInput(),
  11. 'bottomright_x': forms.HiddenInput(),
  12. 'bottomright_y': forms.HiddenInput(),
  13. }
  14. def __init__(self, *args, **kwargs):
  15. self.factor_to_original = kwargs.pop('factor_to_original')
  16. super(TagForm, self).__init__(*args, **kwargs)
  17. def __get_area_value__(self, key):
  18. if len(self.data):
  19. rv = self.data.get(key)
  20. else:
  21. rv = self.get_initial_for_field(self.fields[key], key)
  22. try:
  23. return int(rv)
  24. except TypeError:
  25. return None
  26. except ValueError:
  27. return None
  28. @property
  29. def value_tl_x(self):
  30. return self.__get_area_value__('topleft_x')
  31. @property
  32. def value_tl_y(self):
  33. return self.__get_area_value__('topleft_y')
  34. @property
  35. def value_br_x(self):
  36. return self.__get_area_value__('bottomright_x')
  37. @property
  38. def value_br_y(self):
  39. return self.__get_area_value__('bottomright_y')
  40. @property
  41. def has_valid_coordinates(self):
  42. return is_valid_area(self.value_br_x, self.value_br_y, self.value_tl_x, self.value_tl_y)
  43. def save(self, commit=True):
  44. if self.has_valid_coordinates:
  45. self.instance.topleft_x = self.value_tl_x
  46. self.instance.topleft_y = self.value_tl_y
  47. self.instance.bottomright_x = self.value_br_x
  48. self.instance.bottomright_y = self.value_br_y
  49. else:
  50. self.instance.topleft_x = None
  51. self.instance.topleft_y = None
  52. self.instance.bottomright_x = None
  53. self.instance.bottomright_y = None
  54. return forms.ModelForm.save(self, commit=commit)