Skip to content

Instantly share code, notes, and snippets.

@MattBlack85
Created April 28, 2015 13:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MattBlack85/d45fb4dbfcc4f40313ef to your computer and use it in GitHub Desktop.
Save MattBlack85/d45fb4dbfcc4f40313ef to your computer and use it in GitHub Desktop.
DRF GeometryField
class GeometryExcpetion(Exception):
pass
class GeometryField(serializers.Field):
geom_type = None
def __init__(self, *args, **kwargs):
if not self.geom_type:
raise GeometryException('You must declare a `geom_type` attribute on your field'
'and assign a Geometry class to it')
return super(GeometryField, self).__init__(args, kwargs)
def to_representation(self, obj):
raise ImproperlyConfigured('You need to define your own `to_representation` method')
def to_internal_value(self, data):
try:
geom = GEOSGeometry(data)
if GEOS_CLASSES[geom.geom_typeid] == self.geom_type:
return data
raise serializers.ValidationError(
'Invalid geometry. {geom} required.'.format(geom=self.geom_type))
except ValueError:
raise serializers.ValidationError('Not a valid geometry')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment