加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

在Django模型表单中使用Model属性

发布时间:2020-12-16 21:28:22 所属栏目:Python 来源:网络整理
导读:我试图使用模型属性,如模型形式中的字段,但到目前为止还没有任何运气.结果是表单只呈现模型字段,而不是我定义的属性.知道如何让表单识别添加到模型中的属性吗?我希望将latitude属性添加为表单中的另一个字段. Models.py: class Plot(models.Model): plot_i
我试图使用模型属性,如模型形式中的字段,但到目前为止还没有任何运气.结果是表单只呈现模型字段,而不是我定义的属性.知道如何让表单识别添加到模型中的属性吗?我希望将latitude属性添加为表单中的另一个字段.

Models.py:

class Plot(models.Model):
        plot_id = models.AutoField(primary_key=True)
        plot_number = models.IntegerField(validators=[MinValueValidator(1)],null=False,unique=True)
        geometry = models.PointField(srid=2163,null=True,blank=True) 
        objects = models.GeoManager()

        @property
        def latitude(self):
            self.geometry.transform(4326)
            return self.geometry.y

        @latitude.setter
        def latitude(self,latitude):
            self.geometry.y = latitude

Forms.py:

class InventoryPlotForm(ModelForm):
    class Meta:
        model = ForestInventoryPlot
        exclude = {"geometry"}

解决方法

您的属性不是Field实例,因此ModelForm无法自动为其生成表单字段.您需要在InventoryPlotForm上明确定义纬度字段,并在表单的__init__和save方法中管理其检索和更新.或者,您可以实现自己的Widget类,并告诉InventoryPlotForm将其用于几何字段:
class InventoryPlotForm(ModelForm):
    class Meta(object):
        widgets = {
            'geometry': MyGeometryWidget,}
        ...
    ...

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读