TypeError: float() argument must be a string or a number in Django distance

Sachi Tekina picture Sachi Tekina · Sep 9, 2014 · Viewed 41.2k times · Source

I tried to get the value from my template which is kmdistance but it returns an error when I view the page.

Here's the views.py

def display_maps(request):
    #bases for city proper
    pnt = ButuanMaps.objects.get(clandpin='162-03-0001-017-33').geom

    #landproperty__sownerid__id=5 is for government user
    kmdistance = request.GET.get("kmtocity", None)
    mysection = (request.GET.get("mysection", None))
    query_section = Section.objects.all().order_by('id')
    ...
    query_maps = ButuanMaps.objects.filter(landproperty__sownerid__id=5, geom__distance_lte=(pnt, D(km=kmdistance)), ssectionid__id=mysection)
    ...

Here's the template.html

  <select name="kmtocity" class="form-control">
      <option type="text" value="empty">Select Km. away from City Proper</option>
      <option value="1">1</option>
      <option value="5">5</option>
      <option value="10">10</option>
      <option value="15">15</option>
      <option value="20">20</option>
   </select>

It works fine when I tried putting the value in distance.

Answer

mu 無 picture mu 無 · Sep 9, 2014

You are defaulting to a None value when the kmdistance is not found in the request.GET directory here

kmdistance = request.GET.get("kmtocity", None)

As such, when you convert None to a float later, it throws up an error

TypeError: float() argument must be a string or a number

To overcome this, wherever you are converting to float, just check that the kmdistance value exists, and then convert it to float

if kmdistance is not None:
    kmdistance = float(kmdistance)

Alternatively, use a different default value, like 0 instead of None (though 0 kmdistance may imply wrong value for km distance, so you can use another default value like 100 which works for you)