fields.py 1.2 KB

123456789101112131415161718192021222324252627282930313233
  1. from django import forms
  2. from .widgets import LatLongWidget
  3. class LatLongField(forms.MultiValueField):
  4. widget = LatLongWidget
  5. srid = 4326
  6. default_error_messages = {
  7. 'invalid_latitude' : _('Enter a valid latitude.'),
  8. 'invalid_longitude' : _('Enter a valid longitude.'),
  9. }
  10. def __init__(self, *args, **kwargs):
  11. fields = (forms.FloatField(min_value=-90, max_value=90),
  12. forms.FloatField(min_value=-180, max_value=180))
  13. super().__init__(fields, *args, **kwargs)
  14. def compress(self, data_list):
  15. if data_list:
  16. # Raise a validation error if latitude or longitude is empty
  17. # (possible if LatLongField has required=False).
  18. if data_list[0] in validators.EMPTY_VALUES:
  19. raise forms.ValidationError(self.error_messages['invalid_latitude'])
  20. if data_list[1] in validators.EMPTY_VALUES:
  21. raise forms.ValidationError(self.error_messages['invalid_longitude'])
  22. # SRID=4326;POINT(1.12345789 1.123456789)
  23. srid_str = 'SRID=%d'%self.srid
  24. point_str = 'POINT(%f %f)'%tuple(reversed(data_list))
  25. return ';'.join([srid_str, point_str])
  26. return None