I'm trying to import a KML file into an existing GeoDjango app (using a Postgres 9.3 database). This is my Django model:

class PCT(models.Model):
    code = models.CharField(max_length=3, primary_key=True)
    boundary = models.GeometryField(null=True, blank=True)
    objects = models.GeoManager()

And this is my code [updated to add the relevant part!]:

    filename = 'myfile.KML'
    ds = DataSource(filename)
    lyr = ds[0]
    for feat in lyr:
        code = feat.get('NAME')
        geom = feat.geom
        pct = PCT.objects.get(code=code)
        pct.boundary = geom.json

But when I run it I get this error:

TypeError: Cannot set PCT GeometryProxy (GEOMETRY) with value of type: <class 'django.contrib.gis.gdal.geometries.Polygon'>

What am I doing wrong?

Note that some of the KML features are Polygon and some are MultiPolygon (which I think makes it difficult to use LayerMapping to import the data, which I had ben considering as an alternative approach).


This seems to work (keeping the boundary field as a GeometryField):

    filename = 'myfile.KML'
    ds = DataSource(filename)
    layer_mapping = {
        'code': 'Name',
        'boundary': 'Unknown'
    lm = LayerMapping(PCT, filename, layer_mapping, transform=False)
  • You may try changing your model from a GeometryField to a PolygonField or MultiPolygonField. Im not very familiar with the django gdal/ogr implementation, but it may be checking your geometry types and kicking it back. You may also need to set it to GeometryField.geography, since the input KML will likely be in WGS84 coordinates. – DPierce Mar 28 '15 at 23:16
  • See above. The input KML is indeed in WGS84. I've been reading postgis.refractions.net/documentation/manual-1.5/… and since my data only covers a small country, I'd prefer to use Geometry: but does that mean I need to transform it first before loading it? – Richard Mar 30 '15 at 13:25
  • Geometry is fine for a small area, just try and set your model to models.PolygonField() – DPierce Mar 30 '15 at 23:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.