首页 > 解决方案 > 在单独的表单值发生更改时更新 django 模型表单值

问题描述

我(第一次程序员)正在尝试使用 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 。我怎样才能像这样更新数据?还有其他方法,还是我使用了错误的方法?下面是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)

非常感谢你的帮助。

标签: pythondjangodjango-modelsgeolocation

解决方案


你的问题在这里:

if 'self.address' in Nonprofit.changed_data:

该类Nonprofit没有这样的属性。

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

此外, theNonprofit是一种类型。您正在保存的实例self在您的代码段中被调用。


推荐阅读