简体   繁体   中英

Why I am getting value error in my location finding function?

I need your help to figure out my mistake in my code.

I am trying to auto fill the latitude/longitude fields once user entered the address. So in location field map will be shown and both fields will be auto filled.

models.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

When start my server I saw following two print statements-

Store Location1: 8 SHENTON WAY #43-01 AXA TOWER Singapore
Exception1: not enough values to unpack (expected 2, got 1)

The print statement in longitude functions are never printed.And when I go to my store it shows following error in browser-

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)

Can anyone please help me to find out the exact issue?

You can't unpack an iterable of size one into two variables. Here's the minimal example for your problem.

mystr = 'Store Location1: 8 SHENTON WAY #43-01 AXA TOWER Singapore'

latitude, _ = mystr.split(',')

# ValueError: not enough values to unpack (expected 2, got 1)

Note there is no comma in your input string. Therefore, you need to refactor your logic or ensure your data upstream is appropriate.

For example, if you want location to represent the first split only:

latitude = mystr.split(', ', 1)[0]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM