Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

fields.py 4.2KB

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