1
from django import forms
2
from django.contrib.gis.db.backend import SpatialBackend
3
from django.utils.translation import ugettext_lazy as _
5
class GeometryField(forms.Field):
7
This is the basic form field for a Geometry. Any textual input that is
8
accepted by SpatialBackend.Geometry is accepted by this form. By default,
9
this is GEOSGeometry, which accepts WKT, HEXEWKB, WKB, and GeoJSON.
11
widget = forms.Textarea
13
default_error_messages = {
14
'no_geom' : _(u'No geometry value provided.'),
15
'invalid_geom' : _(u'Invalid geometry value.'),
16
'invalid_geom_type' : _(u'Invalid geometry type.'),
19
def __init__(self, **kwargs):
20
self.null = kwargs.pop('null')
21
self.geom_type = kwargs.pop('geom_type')
22
super(GeometryField, self).__init__(**kwargs)
24
def clean(self, value):
26
Validates that the input value can be converted to a Geometry
27
object (which is returned). A ValidationError is raised if
28
the value cannot be instantiated as a Geometry.
32
# The geometry column allows NULL, return None.
35
raise forms.ValidationError(self.error_messages['no_geom'])
38
# Trying to create a Geometry object from the form value.
39
geom = SpatialBackend.Geometry(value)
41
raise forms.ValidationError(self.error_messages['invalid_geom'])
43
# Ensuring that the geometry is of the correct type (indicated
44
# using the OGC string label).
45
if str(geom.geom_type).upper() != self.geom_type and not self.geom_type == 'GEOMETRY':
46
raise forms.ValidationError(self.error_messages['invalid_geom_type'])