【发布时间】: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