使用ModelForm中的自定义字段值修改模型对象

时间:2013-01-11 17:14:39

标签: django django-forms

我正在Django 1.5上构建一个应用程序,用于存储PostGIS的位置数据。对于原型,创建新位置记录的表单要求用户输入纬度和经度坐标(我认为这将是最简单的编码设置)。

我创建了ModelForm,如此:

class LocationForm(forms.ModelForm):
  # Custom fields to accept lat/long coords from user.
  latitude  = forms.FloatField(min_value=-90, max_value=90)
  longitude = forms.FloatField(min_value=-180, max_value=180)

  class Meta:
    model   = Location
    fields  = ("name", "latitude", "longitude", "comments",)

到目前为止,这么好。但是,Location模型没有latitudelongitude字段。相反,它使用PointField来存储位置的坐标:

from django.contrib.gis.db import models

class Location(models.Model):
  name = models.CharField(max_length=200)
  comments = models.TextField(null=True)

  # Store location coordinates
  coords = models.PointField(srid=4326)

  objects = models.GeoManager()

我正在寻找的是在哪里注入将为latitudelongitude输入获取值的代码,并将它们存储为Point对象Location一旦用户使用有效值提交表单,就会出现coords字段。

例如,我正在寻找与Symfony 1.4的sfFormDoctrine::doUpdateObject()方法相当的Django。

3 个答案:

答案 0 :(得分:2)

stummjr's answer的一些指导和django.forms.BaseModelForm中探讨,我相信我找到了解决方案:

class LocationForm(forms.ModelForm):
  ...

  def save(self, commit=True):
    self.instance.coords = Point(self.cleaned_data["longitude"], self.cleaned_data["latitude"])
    return super(LocationForm, self).save(commit)

答案 1 :(得分:0)

您可以在Location模型中override the save() method

class Location(models.Model):
    name = models.CharField(max_length=200)
    comments = models.TextField(null=True)

    # Store location coordinates
    coords = models.PointField(srid=4326)

    objects = models.GeoManager()

    def save(self, *args, **kwargs):
        self.coords =  ... # extract the coords here passed in through kwargs['latitude'] and kwargs['longitude']
        # don't forget to call the save method from superclass (models.Model)
        super(Location, self).save(*args, **kwargs)

假设您有此视图来处理表单:

  def some_view(request):
      lat = request.POST.get('latitude')
      longit = request.POST.get('longitude')
      ...
      model.save(latitude=lat, longitude=longit)

另一种选择是override the save method in your ModelForm

答案 2 :(得分:0)

  

覆盖表格清洁方法以设置坐标

    def clean(self):
        lat = self.data.get("Longitude")
        long = self.data.get("Latitude")
        p = Point(long,lat,srid=4326)
        self.cleaned_data["coords"] = p
        super(LocationForm, self).clean()