Saturday, May 30, 2015

GeoDjango < 1.7 return GeoJSON passing model name in request

I thought this might be hard but it really was not.  Django 1.8 introduced GeoJSON serializer so use that if you are starting a new project with Django version 1.8 up.  For those stuck with Django version <=1.7  this is the solution for you.

The problem:
You want to pass a model name to a request and return the GeoJSON for some map application.

  1. pip install django-geojson
  2. add 'djgeojson' to your INSTALLED_APPS in the
  3.   add the URL for example:  here we limit the model name to an alpha numeric characture including underscore or dash that is between 5 and 50 characters long
    • url(r'^geojs/(?P<geomodel_name>[-\w]{5,50})/$',geoview.get_geojson, name="get_geojs"),
  4.  should look something like this:
def get_geojson(request, geomodel_name):
    Pas model name as string
    :param geomodel_name: model name as string
    :return: instance of model


    mymodel = apps.get_model('geo_importer', geomodel_name)
    mygeoj = GeoJSONSerializer().serialize(mymodel.objects.all(), use_natural_keys=True, properties=('name', 'id'), srid=3857)

    return HttpResponse(mygeoj, content_type="application/json")

No comments:

Post a Comment