Groovietunes
Groovietunes

Reputation: 663

How to use Django JSON and GeoJSON Serializer?

I am relatively new to Django. I have read the documentation but I'm still having trouble getting it to work.

views.py

def getMarkers(request):
    query = request.GET 
    zoom = query.__getitem__('zoom')
    fromlat = query.__getitem__('fromlat')
    tolat = query.__getitem__('tolat')
    fromlng = query.__getitem__('fromlng')
    tolng = query.__getitem__('tolng')
    querystring = coordinate.objects.filter(lat__gt=fromlat) .filter(lat__lt = tolat).filter(lon__gt = fromlng).filter(lon__lt = tolng)
    data = serialize('geojson', querystring,
          geometry_field='point',
          fields=('name',))

    print(data) 

models.py

class coordinate(models.Model):
    name = models.CharField(max_length=30)
    lat = models.DecimalField(max_digits=10, decimal_places=7)
    lon = models.DecimalField(max_digits=10, decimal_places=7)
    latlng = [lat, lon]
    zoom = models.IntegerField(default=15)

    def __str__(self):
        return self.name

how do I use the searlizer? It's not throwing an error but I know it's not working because nothing is getting printed to the server terminal except the request

Upvotes: 0

Views: 198

Answers (1)

xyres
xyres

Reputation: 21754

print(data) won't work. You have to do something like:

return HttpResponse(data)

Then visit the URL of that view and you'll see the result.

Update

MultiValueDictKeyError occurs if the key that you're trying to access is not in request.GET or request.POST.

To prevent this error, make sure your GET request has zoom key. For that you will need to write the URL in addressbar something like this:

/getmarkers/?zoom=val&formlat=val&somekey=val

Replace val with the value for that key.

Upvotes: 1

Related Questions