Created
April 28, 2015 13:17
-
-
Save MattBlack85/d45fb4dbfcc4f40313ef to your computer and use it in GitHub Desktop.
DRF GeometryField
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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