Debian Codegraph @

django/contrib/gis/forms/fields.py

raw
1 from django import forms
2 from django.contrib.gis.gdal import GDALException
3 from django.contrib.gis.geos import GEOSException, GEOSGeometry
4 from django.core.exceptions import ValidationError
5 from django.utils.translation import gettext_lazy as _
6
7 from .widgets import OpenLayersWidget
8
9
10 class GeometryField(forms.Field):
11 """
12 This is the basic form field for a Geometry. Any textual input that is
13 accepted by GEOSGeometry is accepted by this form. By default,
14 this includes WKT, HEXEWKB, WKB (in a buffer), and GeoJSON.
15 """
16
17 widget = OpenLayersWidget
18 geom_type = "GEOMETRY"
19
20 default_error_messages = {
21 "required": _("No geometry value provided."),
22 "invalid_geom": _("Invalid geometry value."),
23 "invalid_geom_type": _("Invalid geometry type."),
24 "transform_error": _(
25 "An error occurred when transforming the geometry "
26 "to the SRID of the geometry form field."
27 ),
28 }
29
30 def __init__(self, *, srid=None, geom_type=None, **kwargs):
31 self.srid = srid
32 if geom_type is not None:
33 self.geom_type = geom_type
34 super().__init__(**kwargs)
35 self.widget.attrs["geom_type"] = self.geom_type
36
37 def to_python(self, value):
38 """Transform the value to a Geometry object."""
39 if value in self.empty_values:
40 return None
41
42 if not isinstance(value, GEOSGeometry):
43 if hasattr(self.widget, "deserialize"):
44 try:
45 value = self.widget.deserialize(value)
46 except GDALException:
47 value = None
48 else:
49 try:
50 value = GEOSGeometry(value)
51 except (GEOSException, ValueError, TypeError):
52 value = None
53 if value is None:
54 raise ValidationError(
55 self.error_messages["invalid_geom"], code="invalid_geom"
56 )
57
58 # Try to set the srid
59 if not value.srid:
60 try:
61 value.srid = self.widget.map_srid
62 except AttributeError:
63 if self.srid:
64 value.srid = self.srid
65 return value
66
67 def clean(self, value):
68 """
69 Validate that the input value can be converted to a Geometry object
70 and return it. Raise a ValidationError if the value cannot be
71 instantiated as a Geometry.
72 """
73 geom = super().clean(value)
74 if geom is None:
75 return geom
76
77 # Ensuring that the geometry is of the correct type (indicated
78 # using the OGC string label).
79 if (
80 str(geom.geom_type).upper() != self.geom_type
81 and self.geom_type != "GEOMETRY"
82 ):
83 raise ValidationError(
84 self.error_messages["invalid_geom_type"], code="invalid_geom_type"
85 )
86
87 # Transforming the geometry if the SRID was set.
88 if self.srid and self.srid != -1 and self.srid != geom.srid:
89 try:
90 geom.transform(self.srid)
91 except GEOSException:
92 raise ValidationError(
93 self.error_messages["transform_error"], code="transform_error"
94 )
95
96 return geom
97
98 def has_changed(self, initial, data):
99 """Compare geographic value of data with its initial value."""
100
101 try:
102 data = self.to_python(data)
103 initial = self.to_python(initial)
104 except ValidationError:
105 return True
106
107 # Only do a geographic comparison if both values are available
108 if initial and data:
109 data.transform(initial.srid)
110 # If the initial value was not added by the browser, the geometry
111 # provided may be slightly different, the first time it is saved.
112 # The comparison is done with a very low tolerance.
113 return not initial.equals_exact(data, tolerance=0.000001)
114 else:
115 # Check for change of state of existence
116 return bool(initial) != bool(data)
117
118
119 class GeometryCollectionField(GeometryField):
120 geom_type = "GEOMETRYCOLLECTION"
121
122
123 class PointField(GeometryField):
124 geom_type = "POINT"
125
126
127 class MultiPointField(GeometryField):
128 geom_type = "MULTIPOINT"
129
130
131 class LineStringField(GeometryField):
132 geom_type = "LINESTRING"
133
134
135 class MultiLineStringField(GeometryField):
136 geom_type = "MULTILINESTRING"
137
138
139 class PolygonField(GeometryField):
140 geom_type = "POLYGON"
141
142
143 class MultiPolygonField(GeometryField):
144 geom_type = "MULTIPOLYGON"