Django: Saving Foreign Key from Form

两盒软妹~` 提交于 2019-12-07 01:32:34

I'd recommend building a save method on each of your forms which knows how to save itself to the database. It follows a general pattern that "the form performs its action via form.save()" so it should be intuitive to follow.

The bottom line is that right now you have a blanket: "for every field in all forms, set the Thing attribute to those fields".

Since in reality you have per-form save behavior, I think it makes sense to require passing the instance to each form so that each form has a chance to save data in the way appropriate for its fields.

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.

Your view would then become:

for form in form_list:
    form.save(instance)

Just an idea.

If you want to be more DRY about it and like the automation of your other forms, I'd build a base form which has a save method already defined:

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!