[Answered ]-Validate multiple related objects through foreign key field in Django ModelForm

2👍

You can create instances of Coordenada and Endereco in the save() method of LocalizacaoForm, like this:

class LocalizacaoForm(forms.ModelForm):

    # The rest of the form ...
    # ...

    def save(self, commit=False):
        localizacao = super(LocalizacaoForm, self).save(commit=False)

        # create an instance of Coordenada
        coordenada = Coordenada.objects.create(
                        latitude=self.cleaned_data['latitude'],
                        longitude=self.cleaned_data['longitude'],
                        altitude=self.cleaned_data['altitude'],
                        erro_horizontal=self.cleaned_data['erro_horizontal']
                    )

        # create an instance of Endereco
        endereco = Endereco.objects.create(
                        cep=self.cleaned_data['cep'],
                        uf=self.cleaned_data['uf'],
                        localidade=self.cleaned_data['localidade'],
                    )

        # add those instances to localizacao
        localizacao.coordenada_geografica = coordenada
        localizacao.endereco = endereco

        if commit:
            localizacao.save()
        return localizacao
👤xyres

Leave a comment