Python 类型错误:float() 参数必须是 Django 距离中的字符串或数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25735516/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:34:16  来源:igfitidea点击:

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

pythondjangoopenlayers

提问by Sachi Tekina

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

我试图从我的模板中获取值,kmdistance但是当我查看页面时它返回一个错误。

Here's the views.py

这是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

这是模板.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.

当我尝试将值放在距离上时,它工作正常。

采纳答案by u1860929

You are defaulting to a None value when the kmdistanceis not found in the request.GETdirectory here

如果kmdistancerequest.GET此处的目录中找不到,则默认为 None 值

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

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

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

因此,当您稍后将 None 转换为浮点数时,它会引发错误

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

为了克服这个问题,无论您在哪里转换为浮点数,只需检查 kmdistance 值是否存在,然后将其转换为浮点数

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)

或者,使用不同的默认值,例如 0 而不是None(尽管 0 kmdistance 可能意味着 km 距离的值是错误的,因此您可以使用另一个适合您的默认值,例如 100)