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

Updating django model form values upon a change in a separate form value

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

这样做的目的是允许管理员在管理站点中手动输入位置的纬度和经度。但是,如果不这样做,程序应尝试通过使用地理编码器和地址字段来生成这些值。到目前为止,这工作正常。但我现在正在尝试的是在地址更改时自动更新这些值。地址模型更改时,布尔值 refreshCoords 应设置为 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。我怎样才能像这样更新数据?还有其他方法吗,还是我使用了错误的方法?下面是pythonmodels.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:

classNonprofit没有属性.

您可能会想到 Form 实例,它有这样的 属性,但在那个地方不可用。

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