在单独表单值发生更改时更新Django模型表单值

2024-06-16 15:03:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我(第一次程序员)正在尝试用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)

非常感谢你的帮助


Tags: thetoselfnonetruedataifaddress
1条回答
网友
1楼 · 发布于 2024-06-16 15:03:09

你的问题是:

if 'self.address' in Nonprofit.changed_data:

Nonprofit没有这样的属性

您可能正在考虑Form实例,它有这样的属性,但在那个地方不可用

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

相关问题 更多 >