2017-04-11 00:20:14 +02:00
|
|
|
from django import forms
|
|
|
|
from django.core import validators
|
|
|
|
|
2021-02-07 23:15:47 +01:00
|
|
|
|
2017-04-11 00:20:14 +02:00
|
|
|
class LatLonWidget(forms.MultiWidget):
|
|
|
|
"""
|
|
|
|
A Widget that splits Point input into two latitude/longitude boxes.
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, attrs=None, date_format=None, time_format=None):
|
2021-02-07 23:15:47 +01:00
|
|
|
widgets = (forms.HiddenInput(attrs=attrs), forms.HiddenInput(attrs=attrs))
|
2017-04-11 00:20:14 +02:00
|
|
|
super(LatLonWidget, self).__init__(widgets, attrs)
|
|
|
|
|
|
|
|
def decompress(self, value):
|
|
|
|
if value:
|
|
|
|
return tuple(reversed(value.coords))
|
|
|
|
return (None, None)
|
|
|
|
|
|
|
|
|
|
|
|
class LatLonField(forms.MultiValueField):
|
|
|
|
|
|
|
|
widget = LatLonWidget
|
|
|
|
srid = 4326
|
|
|
|
|
|
|
|
default_error_messages = {
|
2021-02-07 23:50:15 +01:00
|
|
|
"invalid_latitude": ("Entrez une latitude valide."),
|
|
|
|
"invalid_longitude": ("Entrez une longitude valide."),
|
2017-04-11 00:20:14 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
def __init__(self, *args, **kwargs):
|
2021-02-07 23:15:47 +01:00
|
|
|
fields = (
|
|
|
|
forms.FloatField(min_value=-90, max_value=90),
|
|
|
|
forms.FloatField(min_value=-180, max_value=180),
|
|
|
|
)
|
2017-04-11 00:20:14 +02:00
|
|
|
super(LatLonField, self).__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:
|
2021-02-07 23:15:47 +01:00
|
|
|
raise forms.ValidationError(self.error_messages["invalid_latitude"])
|
2017-04-11 00:20:14 +02:00
|
|
|
if data_list[1] in validators.EMPTY_VALUES:
|
2021-02-07 23:15:47 +01:00
|
|
|
raise forms.ValidationError(self.error_messages["invalid_longitude"])
|
2017-04-11 00:20:14 +02:00
|
|
|
# SRID=4326;POINT(1.12345789 1.123456789)
|
2021-02-07 23:15:47 +01:00
|
|
|
srid_str = "SRID=%d" % self.srid
|
|
|
|
point_str = "POINT(%f %f)" % tuple(reversed(data_list))
|
|
|
|
return ";".join([srid_str, point_str])
|
2017-04-11 00:20:14 +02:00
|
|
|
return None
|