Groovietunes
Groovietunes

Reputation: 663

Django MultiValueDictKeyError what is it when do they occur and how can it be avoided?

I'm getting a MultiValueDictKeyError in my views.py on my zoom variable. When I remove the zoom variable the error falls on the variable bellow it. So I can assume that this will just follow suite for the rest of the variables. What is a MultiValueDictKeyError and how can they be prevented?

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).filer(zoom_gt=zoom)
    data = serializers.serialize("json", coordinate.objects.all())
    return HttpResponse(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)
    zoom = models.IntegerField(default=15)

Upvotes: 1

Views: 695

Answers (1)

madzohan
madzohan

Reputation: 11808

x.__getitem__(y) == x[y]

so if y is not in GET response python raises KeyError

Use get() method instead of direct access, it returns None (or whatever you set by default kwarg) instead of KeyError

zoom = request.GET.get('zoom')

or

query = request.GET 
zoom = query.get('zoom')

Upvotes: 1

Related Questions