在单独的表单值发生变化时更新 django 模型表单值



我(第一次程序员(正在尝试创建一个使用 django 的网站,其中一个功能是管理员可以将位置和相关信息(如坐标(添加到提要中。

这样做的目的是允许管理员手动在管理站点中输入位置的纬度和经度。但是,如果未执行此操作,程序应尝试通过使用地理编码器和地址字段生成这些值。到目前为止,这工作正常。但是我现在正在尝试的是每当地址更改时自动更新这些值。更改地址模型时,布尔刷新坐标应设置为 true。但是,我在提交管理表单时收到此错误:

AttributeError at /admin/network/nonprofit/add/
type object 'Nonprofit' has no attribute 'changed_data

我不知道现在该怎么办。我在这里使用文档中的changed_data方法:https://docs.djangoproject.com/en/3.0/ref/forms/api/#django.forms.Form.changed_data。如何像这样更新数据?是有其他方法,还是我使用了错误的方法?以下是python models.py 中的相关代码:

class Nonprofit(models.Model):
network = models.ForeignKey(Network, on_delete=models.CASCADE) #Each nonprofit belongs to one network
address = models.CharField(max_length=100, help_text="Enter the nonprofit address, if applicable", null=True, blank=True)
lat = models.DecimalField(max_digits=9, decimal_places=6, null = True, blank=True)
lon = models.DecimalField(max_digits=9, decimal_places=6, null = True, blank=True)
refreshCoords = models.BooleanField(default="False") #GOAL:if this is true, I want to change the coordinates with the geolocator using the address
def save(self, *args, **kwargs):
if 'self.address' in Nonprofit.changed_data: #check to see if the address had changed
self.refreshCoords = True
try:
if self.address and self.lon==None: 
#If there is an address value but not a longitude value, it correctly sets the longitude with the geocoder and address
#This part doesn't really get used with respect to the "refreshCoords" part because this is the initial (no change yet) setting of the coordinate value
self.lon = geolocator.geocode(self.address, timeout=None).longitude
if self.address and self.lat==None:
self.lat = geolocator.geocode(self.address, timeout=None).latitude
if refreshCoords: #if the address has changed, then refresh the coords
self.lon = geolocator.geocode(self.address, timeout=None).longitude
self.lat = geolocator.geocode(self.address, timeout=None).latitude
refreshCoords = False #after the coordinates have been updated with the new address, don't update them until the address is changed again to save loading time
except geopy.exc.GeocoderTimedOut:
print("The geocoder could not find the coordinates based on the address. Change the address to refresh the coordinates.")
super(Nonprofit, self).save(*args, **kwargs)

非常感谢您的帮助。

你的问题在这里:

if 'self.address' in Nonprofit.changed_data:

Nonprofit没有此类属性。

您可能正在考虑Form实例,它具有此类属性,但在该位置不可用。

此外,Nonprofit是一种类型。您正在保存的实例在代码段中称为self

最新更新