#37226 new Bug

Spatial fields should re-raise errors as ValidationError during model validation

Reported by: Jacob Walls Owned by:
Component: GIS Version: 6.0
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

When validating model fields, ValidationError should be raised, according to the full_clean docs. On the contrary, spatial fields don't have any methods to intercept and re-raise errors. I'm suggesting they should.

class GeoJSONGeometry(models.Model):
    geom = models.GeometryField(srid=3857)
    featureid = models.UUIDField(blank=True, null=True)
In [1]: g = GeoJSONGeometry(geom="invalid")

In [2]: g.full_clean()
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[2], line 1
----> 1 g.full_clean()

File ~/django/django/db/models/base.py:1711, in Model.full_clean(self, exclude, validate_unique, validate_constraints)
   1708     exclude = set(exclude)
   1710 try:
-> 1711     self.clean_fields(exclude=exclude)
   1712 except ValidationError as e:
   1713     errors = e.update_error_dict(errors)

File ~/django/django/db/models/base.py:1759, in Model.clean_fields(self, exclude)
   1756     continue
   1757 # Skip validation for empty fields with blank=True. The developer
   1758 # is responsible for making sure they have a valid value.
-> 1759 raw_value = getattr(self, f.attname)
   1760 if f.blank and raw_value in f.empty_values:
   1761     continue

File ~/django/django/contrib/gis/db/models/proxy.py:46, in SpatialProxy.__get__(self, instance, cls)
     42     geo_obj = None
     43 else:
     44     # Otherwise, a geometry or raster object is built using the field's
     45     # contents, and the model's corresponding attribute is set.
---> 46     geo_obj = self._load_func(geo_value)
     47     setattr(instance, self.field.attname, geo_obj)
     48 return geo_obj

File ~/django/django/contrib/gis/geos/geometry.py:776, in GEOSGeometry.__init__(self, geo_input, srid)
    774         input_srid = ogr.srid
    775     else:
--> 776         raise ValueError("String input unrecognized as WKT EWKT, and HEXEWKB.")
    777 elif isinstance(geo_input, GEOM_PTR):
    778     # When the input is a pointer to a geometry (GEOM_PTR).
    779     g = geo_input

ValueError: String input unrecognized as WKT EWKT, and HEXEWKB.

Change History (0)

Note: See TracTickets for help on using tickets.
Back to Top