Handle GeoDjango Polygon Geometry fields
| 6 | from rest_framework.fields import Field |
| 7 | |
| 8 | class PolygonGeometryField(Field): |
| 9 | """ |
| 10 | Handle GeoDjango Polygon Geometry fields |
| 11 | """ |
| 12 | |
| 13 | type_name = 'PolygonGeometryField' |
| 14 | |
| 15 | def to_representation(self, value): |
| 16 | if isinstance(value, dict) or value is None: |
| 17 | return value |
| 18 | |
| 19 | if value.geojson: |
| 20 | try: |
| 21 | geojson = json.loads(value.geojson) |
| 22 | except ValueError: |
| 23 | geojson = {'type': 'Polygon', 'coordinates': []} |
| 24 | else: |
| 25 | geojson = {'type': 'Polygon', 'coordinates': []} |
| 26 | |
| 27 | return geojson |
| 28 | |
| 29 | def to_internal_value(self, value): |
| 30 | if value == '' or value is None: |
| 31 | return value |
| 32 | |
| 33 | if isinstance(value, GEOSGeometry): |
| 34 | return value |
| 35 | if isinstance(value, dict): |
| 36 | if value.get('geometry'): |
| 37 | value = value['geometry'] |
| 38 | value = json.dumps(value) |
| 39 | |
| 40 | try: |
| 41 | return GEOSGeometry(value) |
| 42 | except GEOSException: |
| 43 | raise ValidationError('Invalid format: not GeoJSON') |
| 44 | except (ValueError, TypeError, GDALException) as e: |
| 45 | raise ValidationError('Unable to create GEOSGeometry') |
| 46 |