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.
'''
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")
The problem:
You want to pass a model name to a request and return the GeoJSON for some map application.
- pip install django-geojson
- add 'djgeojson' to your INSTALLED_APPS in the settings.py
- urls.py 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"),
- views.py should look something like this:
'''
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")
Comments
Post a Comment