1

I am trying to write the view that will return a GeoJSON of my model stored in the database. I would like to create an API so that I can use an AJAX request in a JavaScript file I have. I have not been able to find how to use the Django REST Framework GIS serializers in my views. I simply want to create an API that returns the GeoJSON to load in my Leaflet map.

Views.py

from django.shortcuts import render
from django.core.serializers import serialize
from .serializers import GeoJsonSerializer
from .models import UtmZones
# Create your views here.
def index(request):
    context = {}
    return render(request, 'proj_picker/proj.html', context)

def api_get_utm(request):
    utm_poly = serialize('geojson', UtmZones.objects.all(), geometry_field='mpoly')
    return JsonResponse(utm_poly, safe=False)

models.py

from django.contrib.gis.db import models

# Create your models here.
class UtmZones(models.Model):
    swlon = models.CharField(max_length=254)
    swlat = models.CharField(max_length=254)
    hemisphere = models.CharField(max_length=3)
    zone = models.CharField(max_length=5)
    cm = models.CharField(max_length=5)
    zone_hemi = models.CharField(max_length=5)

    mpoly = models.MultiPolygonField()

    def __str__(self):
        return self.zone

urls.py

from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='proj'),
    path('api/utm/', views.api_get_utm, name='utm'),
]
  • what database are you using? – ziggy Jun 28 at 13:15
  • PostgreSQL with PostGIS extension. – Flynnpc Jun 28 at 13:50
  • it seems like you need to add the api_get_utm to the urls.py – ziggy Jun 28 at 13:54
0

your workflow looks fine but give my below query a try

def api_get_utm(request):
   cur = conn.cursor()
   qry='''SELECT row_to_json(fc)
          FROM
           ( SELECT 'FeatureCollection' AS TYPE,
                   array_to_json(array_agg(f)) AS features
           FROM
             (SELECT 'Feature' AS TYPE,
                     ST_AsGeoJSON(g.geom,4326)::JSON AS geometry,
                     row_to_json(
                                   (SELECT p
                                    FROM
                                      ( SELECT "INSERT FIELD NAMES") AS p)) AS properties
              FROM "TABLE NAME" AS g
              ) AS f) AS fc;
      '''
   cur.execute(qry)
   row=cur.fetchone()
   return JsonResponse(row[0])
0

I found out how to do it with Django 2.2's serializer so I didn't need DRF-gis. My problem was the JsonResponse was unecessary because I had already serialized it as a json. The following code works.

from django.shortcuts import render
from django.core.serializers import serialize
from django.http import HttpResponse
from .models import UtmZones

# Create your views here.
def index(request):
    context = {}
    return render(request, 'proj_picker/proj.html', context)

def api_get_utm(request):
    utm_poly = serialize('geojson', UtmZones.objects.all(), geometry_field='mpoly', fields=('zone', 'zone_hemi'))
    return HttpResponse(utm_poly, content_type='application/json')

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.