此致
我需要在两个或更多模型中同时保存我在表单中提交的数据,如何使用form_valid对此进行验证?我试过这个但没有成功:
class PEPropietarioView(UpdateModelMixin,UpdateView):
model = Propietario
form_class = FormPropietario
success_url = '/'
template_name = 'productores/PE/propietario.html'
def form_valid(self,form):
admin = Administrador()
enc = Encargado()
admin = form.save()
enc = form.save()
return super(PEPropietarioView,self).form_valid(form)
如何实现保存我在FormPropietario中提交的数据,同时保存在Administrador和Encargado模型中?
答案 0 :(得分:1)
在FormPropietario表单中添加一个方法:
class FormPropietario(forms.Form):
...
def save_relateds(self):
admin = Administrador.objects.get_or_create(**self.cleaned_data)
enc = Encargado.objects.get_or_create(**self.cleaned_data)
return True
然后叫它:
def form_valid(self, form):
form.save_relateds()
return super(PEPropietarioView,self).form_valid(form)