Search code examples
djangokmlgeodjango

Adding a KML file into a GeoDjango field


I'm trying to add a KML file to a field in GeoDjango. Link to KML file. I tried to follow the answer on this question but it's mostly wrong.

My model:

class School(models.Model):
    boundaries = models.PolygonField(null=True)

i = School.objects.get(...)
ds = DataSource('school.aspx')
layer = ds[0]   #The file only has 1 layer
geom = layer.get_geoms()
boundary = GEOSGeometry(geom[0])
i.boundaries = boundary
i.save()

The above code gives me the following error:

TypeError: Improper geometry input type: <class 'django.contrib.gis.gdal.geometries.Polygon'>


When I try to add the field directly, like this:

i = School.objects.get(...)
ds = DataSource('school.aspx')
layer = ds[0]
geom = layer.get_geoms()
i.boundaries = geom[0]
i.save()

I get this error: TypeError: Cannot set School SpatialProxy (POLYGON) with value of type: <class 'django.contrib.gis.gdal.geometries.Polygon'>

How do I save the polygon shape in the KML file into my database? I'm stumped.


Solution

  • Try using the .geos property of gdal geoms:

    ds = DataSource('school.kml')
    o = School(boundaries=ds[0][0].geom.geos)
    o.save()