123456789101112131415161718192021222324252627282930313233 |
- from django import forms
- from .widgets import LatLongWidget
- class LatLongField(forms.MultiValueField):
- widget = LatLongWidget
- srid = 4326
- default_error_messages = {
- 'invalid_latitude' : _('Enter a valid latitude.'),
- 'invalid_longitude' : _('Enter a valid longitude.'),
- }
- def __init__(self, *args, **kwargs):
- fields = (forms.FloatField(min_value=-90, max_value=90),
- forms.FloatField(min_value=-180, max_value=180))
- super().__init__(fields, *args, **kwargs)
- def compress(self, data_list):
- if data_list:
- # Raise a validation error if latitude or longitude is empty
- # (possible if LatLongField has required=False).
- if data_list[0] in validators.EMPTY_VALUES:
- raise forms.ValidationError(self.error_messages['invalid_latitude'])
- if data_list[1] in validators.EMPTY_VALUES:
- raise forms.ValidationError(self.error_messages['invalid_longitude'])
- # SRID=4326;POINT(1.12345789 1.123456789)
- srid_str = 'SRID=%d'%self.srid
- point_str = 'POINT(%f %f)'%tuple(reversed(data_list))
- return ';'.join([srid_str, point_str])
- return None
|