我需要你的帮助来找出代码中的错误。
我试图在用户输入地址后自动填充纬度/经度字段。因此,在位置字段中将显示 map ,并且两个字段都将自动填充。
模型.py:
from location_field.models.plain import PlainLocationField
class Store(models.Model):
building = models.ForeignKey(Building, related_name='building', on_delete=models.SET_NULL, blank=True, null=True)
address = models.TextField(default='Singapore')
latitude = models.FloatField(validators=[MinValueValidator(-90.0), MaxValueValidator(90.0)])
longitude = models.FloatField(validators=[MinValueValidator(-180.0), MaxValueValidator(180.0)])
location = PlainLocationField(based_fields=['address'], zoom=7, null=True)
@property
def latitude(self):
if not self.location:
return
try:
print('Store Location1: ' + str(self.location))
latitude, _ = self.location.split(',')
except Exception as e:
print('Exception1: ' + str(e))
print("latitude:", latitude)
return latitude
@property
def longitude(self):
if not self.location:
return
try:
print('Store Location2: ' + str(self.location))
_, longitude = self.location.split(',')
except Exception as e:
print('Exception2: ' + str(e))
print("longitude:", longitude)
return longitude
当启动我的服务器时,我看到以下两个打印语句 -
Store Location1: 8 SHENTON WAY #43-01 AXA TOWER Singapore
Exception1: not enough values to unpack (expected 2, got 1)
经度函数中的打印语句永远不会被打印。当我去我的商店时,它在浏览器中显示以下错误 -
File "E:\mysite\models.py", line 216, in latitude
latitude, _ = self.location.split(',')
Exception Type: ValueError
Exception Value:not enough values to unpack (expected 2, got 1)
谁能帮我找出确切的问题吗?
最佳答案
您无法将大小为 1 的可迭代对象解压为两个变量。这是您的问题的最小示例。
mystr = 'Store Location1: 8 SHENTON WAY #43-01 AXA TOWER Singapore'
latitude, _ = mystr.split(',')
# ValueError: not enough values to unpack (expected 2, got 1)
请注意,您的输入字符串中没有逗号。因此,您需要重构您的逻辑或确保您的上游数据是合适的。
例如,如果您希望 location
仅代表第一个分割:
latitude = mystr.split(', ', 1)[0]
关于python - 为什么我的位置查找功能出现值错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50946509/