fields.py 4.4 KB

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