首页 > 解决方案 > GeoDjango:ValueError,无法将字符串转换为浮点数

问题描述

昨天我在这个简单的模型上遇到了同样的问题,我已经设法解决了这个问题。

今天我修改了以下模型

from django.contrib.gis.db import models
from django.contrib.gis.geos import Point

from mapbox_location_field.models import LocationField

class IllegalDumpCategory(models.Model):
    category = models.CharField(
        max_length=50,
    )
    slug = models.SlugField(
        max_length=50,
        unique=True,
    )
    description = models.TextField(
        max_length=500,
    )


class IllegalDumpGeo(models.Model):
    user_name = models.CharField(
        'Username',
        max_length=50,
    )
    user_name_email = models.EmailField(
        'Email',
        max_length=254,
    )
    description = models.TextField(
        max_length=500,
    )
    image_1 = models.ImageField(
        upload_to='%Y/%m/%d',
        blank=False,
        null=False,
    )
    image_2 = models.ImageField(
        upload_to='%Y/%m/%d',
        blank=True,
        null=True,
    )
    image_3 = models.ImageField(
        upload_to='%Y/%m/%d',
        blank=True,
        null=True,
    )
    volume_extension = models.PositiveIntegerField(
        blank=False,
        null=False,
    )
    link = models.URLField(
        blank=True,
        null=True,
    )
    waste_type = models.ForeignKey(
        IllegalDumpCategory,
        on_delete=models.CASCADE,
    )
    geom = models.PointField(
        blank=True,
        null=True,
    )
    location = LocationField()


    def __int__(self):
        return self.pk

    def save(self, *args, **kwargs):
        lat = self.location[0]
        lon = self.location[1]
        self.geom = Point(x=lon, y=lat, srid=4326)
        super(IllegalDumpGeo, self).save(*args, **kwargs)

    @property
    def coordinates(self):
        return str(self.geom.x) + ', ' + str(self.geom.y)

我正在尝试通过管理面板添加一些点,但我再次看到此错误:

ValueError could not convert string to float:
'6.01245266838146,-10.16992187499897'

为什么会这样?

在这里追溯

标签: pythondjangodjango-modelsmapboxgeodjango

解决方案


该错误实际上是 django-mapbox-location-field 中的错误

编辑此文件的第 6 行:mapbox_location_field/widgets.py 并将其更改为:

def parse_tuple_string(tuple_string): return tuple(map(float, tuple_string[1:-1].split(",")))

注意我在 split 方法中删除了逗号后的空格。

这解决了它。我想我应该发个 PR


推荐阅读