Django:从表单保存外键

时间:2013-10-04 19:05:56

标签: python django forms foreign-keys django-formwizard

这是this question的延续,其中我试图弄清楚如何构造由lat / lon FloatFields组成的PointField。我采用了@ Simon的建议,并将我的模型重组为:

class Point(models.Model):
   lat = models.FloatField()
   lon = models.FloatField()

class Thing(models.Model):
   point = models.ForeignKey(Point)

我的表单有两个字段,对应于谷歌地图的经度和纬度坐标值:

class StepThreeForm(forms.Form):
    lat = forms.FloatField()
    lon = forms.FloatField()
    ...

然而,由于显而易见的原因,这不起作用,但我不确定如何解决它。为了澄清,我试图有两个表单字段对应于latlon的外键值。这是补充信息(我正在使用FormWizard和forms.Form):


url(r'^mapform/$', login_required(MyWizard.as_view([StepOneForm, StepTwoForm, StepThreeForm])), name='create'),

class MyWizard(SessionWizardView):  ## this view also serves to edit existing objects and provide their instances
    def done(self, form_list, **kwargs):
        id = form_list[0].cleaned_data['id']
        try:
            thing = Thing.objects.get(pk=id)
            instance = thing
        except:
            thing = None
            instance = None
        if thing and thing.user != self.request.user:
            raise HttpResponseForbidden()
        if not thing:
            instance = Thing()
            for form in form_list:
                for field, value in form.cleaned_data.iteritems():
                    setattr(instance, field, value)
            instance.user = self.request.user
            instance.save()
        return render_to_response('wizard-done.html', {
                'form_data': [form.cleaned_data for form in form_list],})

我感谢任何建议和帮助!


编辑:根据Yuji Tomita的输入进行更新。其中大部分都很有意义(谢谢!),但我不确定它为什么会导致ValueError。

class MyWizard(SessionWizardView):
     ....
            for form in form_list:
                form.save(instance)
     ...

class StepOneForm(forms.Form):
     ...
     def save(self, thing):
        for field, value in self.cleaned_data.items():
            setattr(thing, field, value)

class StepTwoForm(forms.Form):
     ...
     def save(self, thing):
        for field, value in self.cleaned_data.items():
            setattr(thing, field, value)

我相信我应该将表单字段保留为lat和lon,因为我在表单中使用google地图并从选定的输入中获取lat和lon,然后根据这些值构建点字段:

class StepThreeForm(forms.Form):
    lat = forms.FloatField()
    lon = forms.FloatField()

    def save(self, thing):
        thing.point = Point.objects.get_or_create(lat=self.cleaned_data.get('lat'), lon=self.cleaned_data.get('lon'))

这会产生ValueError: Cannot assign "(<Point: Point object>, False)": "Thing.point" must be a "Point" instance.

Traceback:
File "/lib/python2.7/django/core/handlers/base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "/lib/python2.7/django/contrib/auth/decorators.py" in _wrapped_view
  20.                 return view_func(request, *args, **kwargs)
File "/lib/python2.7/django/views/generic/base.py" in view
  48.             return self.dispatch(request, *args, **kwargs)
File "/lib/python2.7/django/contrib/formtools/wizard/views.py" in dispatch
  223.         response = super(WizardView, self).dispatch(request, *args, **kwargs)
File "/lib/python2.7/django/views/generic/base.py" in dispatch
  69.         return handler(request, *args, **kwargs)
File "/lib/python2.7/django/contrib/formtools/wizard/views.py" in post
  286.                 return self.render_done(form, **kwargs)
File "/lib/python2.7/django/contrib/formtools/wizard/views.py" in render_done
  328.         done_response = self.done(final_form_list, **kwargs)
File "/myproject/myapp/forms.py" in done
  93.       form.save(instance)
File "/myproject/myapp/forms.py" in save
  67.         thing.point = Thing.objects.get_or_create(lat=self.cleaned_data.get('lat'), lon=self.cleaned_data.get('lon'))
File "/lib/python2.7/django/db/models/fields/related.py" in __set__
  366.                                  self.field.name, self.field.rel.to._meta.object_name))

1 个答案:

答案 0 :(得分:3)

我建议在每个表单上构建一个save方法,知道如何将自己保存到数据库中。它遵循一般模式“表单通过form.save()执行其操作”,因此应该直观地遵循。

最重要的是,现在你有了一条毯子:“对于所有形式的每个字段,将Thing属性设置为这些字段”。

因为实际上你有每个表单的保存行为,我认为要求将实例传递给每个表单是有意义的,这样每个表单都有机会以适合其字段的方式保存数据。

class Form1(...):
   def save(self, thing):
      for field, value in self.cleaned_data.items():
          setattr(thing, field, value)

class Form2(...):
   def save(self, thing):
      thing.point = Point.objects.get_or_create(lat=self.cleaned_data.get('lat'), long=...)
      # note, you may not want get_or_create if you don't want to share points.

您的观点将变为:

for form in form_list:
    form.save(instance)

只是一个想法。

如果你想对它更加干嘛并喜欢其他表单的自动化,我会构建一个基本表单,其中已经定义了一个save方法:

class BaseSaveBehaviorForm(forms.Form):
     def save(self, thing):
         for field, value in self.cleaned_data.items():
             setattr(thing, field, value)

class NormalBehaviorForm(BaseSaveBehaviorForm):
     # your forms as usual


class SpecialSaveBehaviorForm(forms.Form):
     def save(self, instance):
         # do something unusual