Skip to content

Commit

Permalink
Add GeometrySizeValidator to limit area
Browse files Browse the repository at this point in the history
  • Loading branch information
bkg committed Dec 7, 2016
1 parent 91b1169 commit c51c1b9
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
21 changes: 21 additions & 0 deletions spillway/validators.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from django import forms
from django.utils.deconstruct import deconstructible
from django.utils.translation import ugettext_lazy as _


@deconstructible
class GeometrySizeValidator(object):
"""Field validator to limit geometries to a given area."""
message = _('Max area exceeded.')
code = 'invalid'

def __init__(self, max_area, srid=None):
self.max_area = max_area
self.srid = srid

def __call__(self, geom):
if self.srid and geom.srid != self.srid:
geom.transform(self.srid)
if (getattr(geom, 'ogr', geom).dimension > 1 and
geom.area > self.max_area):
raise forms.ValidationError(self.message, code=self.code)
6 changes: 6 additions & 0 deletions tests/test_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

from spillway.forms.fields import OGRGeometryField, GeometryFileField
from spillway.collections import Feature, NamedCRS
from spillway.validators import GeometrySizeValidator
from .models import _geom


Expand Down Expand Up @@ -41,6 +42,11 @@ def test_feature_srid(self):
def test_invalid(self):
self.assertRaises(forms.ValidationError, self.field.to_python, '3')

def test_size_validator(self):
validator = GeometrySizeValidator(3 ** 2, 4326)
field = OGRGeometryField(validators=[validator])
self.assertRaises(forms.ValidationError, field.clean, '0,0,5,5')

def test_srid(self):
srid = 4269
geom = OGRGeometryField(srid=srid).to_python('POINT(0 0)')
Expand Down

0 comments on commit c51c1b9

Please sign in to comment.