【问题标题】:converting float to decimal (IP address parameter)将浮点数转换为十进制(IP 地址参数)
【发布时间】:2010-12-10 21:24:28
【问题描述】:

我正在尝试使用 GeoIP 来定位用户的位置,我有

Class register(models.Model): 

        user = models.ForeignKey('auth.User', unique = True) 
        latitude = models.DecimalField(max_digits=12, decimal_places=10)
        longitude = models.DecimalField(max_digits=12, decimal_places=10)
        Availability  = models.CharField(max_length=8,choices=STATUS_CHOICES, blank= False, null=False)
        Status = models.CharField(max_length=50, blank = True, null= True)

在forms.py中我有

class registerForm(forms.ModelForm): 
        class Meta:
            model=register
            fields = ('Availability', 'Status')#'latitude','longitude',

        def save(self,ip_address, *args, **kwargs):
            g = GeoIP()
            lat,lon = g.lat_lon(ip_address)
            user_location = super(registerForm, self).save(commit=False)
            user_location.latitude = lat
            user_location.longitude = lon
            user_location.save(*args, **kwargs)

在我看来我有

def status_set(request):
    if request.method == "POST":
        rform = registerForm(data = request.POST)
    print "rejister form request"
        if rform.is_valid():
            register = rform.save(ip_address='119.153.117.32')
            register.user=request.user
                register.save(ip_address)
                    return render_to_response('home.html')
    else:
        rform = registerForm() 
    return render_to_response('status_set.html',{'rform':rform}) 

我将 IP 地址设为“119.153.117.32”,因为我从本地循环访问该站点,而 GeoIP 没有本地循环 (127.0.0.1) 的纬度、经度。对于本地循环,它没有返回任何内容。\ 当我提交表单时,它显示“无法将浮点数转换为十进制。首先将浮点数转换为字符串”。我该如何解决这个问题是必须将其转换为字符串还是有更好的方法。

【问题讨论】:

    标签: django django-forms geoip


    【解决方案1】:

    尝试使用 models.FloatField 作为坐标而不是 DecimalField,或者在保存对象之前使用 str(lat) 等将浮点数转换为字符串。我不确定 DecimalField 是否适合作为浮点数返回的数据,所以我更愿意更改为 FloatField,但这意味着重新同步您的数据库。

    DecimalField 可能适用于 python 'decimal' 的内容 - 请参见此处:

    http://docs.python.org/library/decimal.html

    【讨论】:

      猜你喜欢
      • 2014-03-01
      • 2013-11-13
      • 1970-01-01
      • 1970-01-01
      • 2017-04-23
      • 2010-12-08
      • 2014-11-24
      • 2017-02-18
      相关资源
      最近更新 更多