问候,

我需要同时在两个或多个模型中保存在表单中提交的数据,如何使用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模型中提交的数据?

===============>>#1 票数: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)

  ask by dfrojas translate from so

未解决问题?本站智能推荐: