【问题标题】:Django - Transform an address in latitude and longitude through Google API and save the objectDjango - 通过 Google API 转换经纬度地址并保存对象
【发布时间】:2019-02-18 19:38:27
【问题描述】:

我有一个地址模型,我将地址保存在不同的字段中:

  • address_1
  • address_2
  • 邮编
  • 城市
  • 国家
  • 纬度
  • 经度

首先,我要求用户用地址填写表格(没有纬度和经度,默认情况下它们设置为“0”)。然后我尝试在保存对象之前使用 Google API 将此地址转换为纬度和经度。

这是我的代码。我不知道这是否是正确的方法,但现在它不起作用,我收到错误

'float' 对象没有属性'save'

知道如何解决这个问题吗? 非常感谢。(我是编程新手,也是 Django 新手)

from django.db import models
from django.contrib.auth.models import User
from users.models import Profile
from django_countries.fields import CountryField
import requests


class Address(models.Model):
    profile = models.OneToOneField(Profile, on_delete=models.CASCADE)
    address_1 = models.CharField(max_length=255, blank=True)
    address_2 = models.CharField(max_length=255, blank=True)
    zip_code = models.IntegerField(blank=True, null=True)
    city = models.CharField(max_length=255, blank=True)
    country = CountryField(blank=True)
    latitude = models.DecimalField(
        max_digits=9, decimal_places=6, blank=True, default='0')
    longitude = models.DecimalField(
        max_digits=9, decimal_places=6, blank=True, default='0')

    def __str__(self):
        return f'Adresse de {self.profile.user.username}'

    class Meta:
        verbose_name_plural = "addresses"

    def save(self, **kwargs):
        super().save(**kwargs)

        address = " ".join(
            [self.address_1, self.address_2, str(self.zip_code), self.city])
        api_key = "PROJECT_API_KEY"
        api_response = requests.get(
            'https://maps.googleapis.com/maps/api/geocode/json?address={0}&key={1}'.format(address, api_key))
        api_response_dict = api_response.json()

        if api_response_dict['status'] == 'OK':
            self.latitude = api_response_dict['results'][0]['geometry']['location']['lat']
            self.longitude = api_response_dict['results'][0]['geometry']['location']['lng']
            self.save()

【问题讨论】:

  • 你应该在定义的最后使用这个:super().save(**kwargs)
  • @vctrd 您的评论解决了问题:) 非常感谢。我还读到最好为这种函数创建一个 utils.py 文件。这是下一步!

标签: django api google-maps django-models


【解决方案1】:

正如@vctrd 所指出的,我应该将 super().save(**kwargs) 放在函数的末尾。现在它正在工作。

【讨论】:

    猜你喜欢
    • 2013-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-24
    • 1970-01-01
    • 2010-09-11
    • 1970-01-01
    相关资源
    最近更新 更多