Update in three models at the same time in form_valid django

…衆ロ難τιáo~ 提交于 2020-01-06 21:07:18

问题


I have three models, Propietario, Administrador and Encargado. And I have three forms with ModelForm calling each of these models. The forms may to have three options depends of the user does:

  1. If user picked option A, will display three forms where can fill different data for each form

  2. If user picked option B, will display two forms, where the data filled in the form FormPropietario will save in Propietario model and automatically in Administrator model the same data. And the second form would be the form of Encargado model.

  3. If user picked option C, will display only one form where the data filled here will save in all three models.

Note: Data filled in any of model will replace the other one, not has to create a new one. I mean, If user at the beginning picked option A and filled three different data, and then choose option C, the data filled in option C has to replace data in the other models, not has to create a new one.

To achieve this, i have been trying with this code:

Forms:

class FormPropietario(ModelForm):
    def __init__(self, *args, **kwargs):
        super(FormPropietario, self).__init__(*args, **kwargs)
        for field_name, field in self.fields.items():
            field.widget.attrs['class'] = 'input-medium'
            self.fields['primer_nombre'].widget.attrs['required'] = True
    class Meta():
        model = Propietario
        exclude = ("predio",'rol',)
        widgets = {
            'fecha_nacimiento' : forms.DateInput(attrs={'type':'date'}),
        }

class FormAdministrador(ModelForm):
    def __init__(self, *args, **kwargs):
        super(FormAdministrador, self).__init__(*args, **kwargs)
        for field_name, field in self.fields.items():
            field.widget.attrs['class'] = 'input-medium'
            self.fields['primer_nombre'].widget.attrs['required'] = True
    class Meta():
        model = Administrador
        exclude = ("predio",'rol')


class FormEncargado(ModelForm):
    def __init__(self, *args, **kwargs):
        super(FormEncargado, self).__init__(*args, **kwargs)
        for field_name, field in self.fields.items():
            field.widget.attrs['class'] = 'input-medium'
            self.fields['primer_nombre'].widget.attrs['required'] = True
    class Meta():
        model = Encargado
        exclude = ("predio",'rol',)

The view that handles the option A, works fine:

#PAE
class PAEPropietarioView(UpdateModelMixin,UpdateView):
    model = Propietario
    form_class = FormPropietario
    success_url = '/'
    template_name = 'productores/PAE/propietario.html'

    def form_valid(self,form):
        propietario = Propietario()
        propietario = form.save(commit=False)
        propietario.rol.add(1)
        return super(PAEPropietarioView,self).form_valid(form)

But problem is the view that handles the option B or C. I have this right now but with no success:

class PropietarioAndAdministratorView(UpdateModelMixin,UpdateView):
    model = Propietario
    form_class = FormPropietario
    success_url = '/'
    template_name = 'productores/PE/propietario.html'

    def form_valid(self, form):
        is_valid = super(PropietarioAndAdministratorView,self).form_valid(form)
        if is_valid:
            admin = Administrador.objects.get_or_create(predio_id=self.kwargs['predio_id'],**form.cleaned_data)
            return True
        return False

I also tried with this line, but nothing happens:

def form_valid(self, form):
        Administrador.objects.get_or_create(predio_id=1,**form.cleaned_data)
        return super(PropietarioAndAdministratorView, self).form_valid(form)

I think that I'm close, but the following line has an error; effectively saves in Administrator but save it twice, one with the data and other one empty. Why?

Administrador.objects.get_or_create(predio_id=self.kwargs['predio_id'],**form.cleaned_data)

I have been working on that for days and I cant get to put it works, how can I achieve it? Thanks in advance.

来源:https://stackoverflow.com/questions/30282885/update-in-three-models-at-the-same-time-in-form-valid-django

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