Validate multiple related objects through foreign key field in Django ModelForm

Hannon César

In the example shown by the code below, is it possible to automatically validate and create instances of Endereco and Coordenada using LocalizacaoForm?

The reason why I want to do this is so that I can use Generic Views as much as possible, and they don't work well (at least not out-of-the-box) with more than one ModelForm per view.

In the application, I want to render a LocalizacaoForm and show the fields from Endereco and Coordenada as well. What I am doing in so far doesn't seem to solve it, because self.fields.update(fields_for_model(Coordenada)) only creates the input fields, not an actual instance of Coordenada. Therefore I get a django NOT NULL constraint failed id for the object coordenada.

Is there a way to do what I want or should I just stick with rendering each form separately?

#models.py
class Coordenada(models.Model):
    latitude = models.FloatField()
    longitude = models.FloatField()
    altitude = models.FloatField()
    erro_horizontal = models.FloatField()

class Endereco(models.Model):
    cep = models.IntegerField()
    uf = models.CharField(max_length=2)
    localidade = models.CharField(max_length=50)  # nome da cidade
    # other fields...

class Localizacao(models.Model):
    endereco = models.OneToOneField(Endereco)
    coordenada_geografica = models.ForeignKey('Coordenada')

#forms.py
class LocalizacaoForm(forms.ModelForm):

    def __init__(self, instance=None, *args, **kwargs):
        super(LocalizacaoForm, self).__init__(instance=instance, *args, **kwargs)
        # Retrieve the fields from Endereco and Coordenada model and update the fields with it
        self.fields.update(fields_for_model(Endereco))
        self.fields.update(fields_for_model(Coordenada))

    class Meta:
        model = Localizacao
        exclude = ('endereco', 'coordenada_geografica')

#views.py
class LocalizacaoCreateView(generic.CreateView):
    model = Localizacao
    form_class = LocalizacaoForm
    template_name = 'localizacao_create_form.html'
xyres

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

How can I list all foreign key related objects in Django admin panel?

From Dev

Foreign Keys clash with related field in Django Model

From Dev

How to make a modelform editable foreign key field in a django template?

From Dev

Group django queryset by foreign key / related field

From Dev

How to Stop Django ModelForm From Creating Choices for a Foreign Key

From Dev

Updating foreign key field in Django

From Dev

Iterating through all foreign key related children of an abstract django model

From Dev

django filtering on a field in a foreign key object

From Dev

Django Multiple Foreign Key Model

From Dev

Django admin foreign key field filtering

From Dev

Django multiple Foreign Key - Display related field in details admin page for add/edit

From Dev

Django: how to get related foreign key set?

From Dev

Displaying foreign key attributes in ModelForm Django

From Dev

Django ModelForm - Create instance with foreign key

From Dev

How to get a list of of objects of a Django model using a field that itself is a foreign key?

From Dev

foreign key as initial value not passed to the ModelForm in django

From Dev

Django models: Aggregate Sum over multiple foreign key field values

From Dev

Cannot generate foreign key field in Django

From Dev

Limit choices and validate django's foreign key to related objects (also in REST)

From Dev

Django - Validate a disabled field in modelform_factory

From Dev

Modelform prepopulate foreign key

From Dev

Updating foreign key field in Django

From Dev

Django filter form field by Foreign Key

From Dev

Displaying foreign key attributes in ModelForm Django

From Dev

Django restframework: Validate a related field with a list of IDs

From Dev

iterate through certain number of foreign key objects

From Dev

Django Form with Foreign Key Related Data

From Dev

Autoincrement-like field for objects with the same foreign key (Django 1.8, MySQL 5.5)

From Dev

how to filter a model objects by related table's foreign key in django REST

Related Related

  1. 1

    How can I list all foreign key related objects in Django admin panel?

  2. 2

    Foreign Keys clash with related field in Django Model

  3. 3

    How to make a modelform editable foreign key field in a django template?

  4. 4

    Group django queryset by foreign key / related field

  5. 5

    How to Stop Django ModelForm From Creating Choices for a Foreign Key

  6. 6

    Updating foreign key field in Django

  7. 7

    Iterating through all foreign key related children of an abstract django model

  8. 8

    django filtering on a field in a foreign key object

  9. 9

    Django Multiple Foreign Key Model

  10. 10

    Django admin foreign key field filtering

  11. 11

    Django multiple Foreign Key - Display related field in details admin page for add/edit

  12. 12

    Django: how to get related foreign key set?

  13. 13

    Displaying foreign key attributes in ModelForm Django

  14. 14

    Django ModelForm - Create instance with foreign key

  15. 15

    How to get a list of of objects of a Django model using a field that itself is a foreign key?

  16. 16

    foreign key as initial value not passed to the ModelForm in django

  17. 17

    Django models: Aggregate Sum over multiple foreign key field values

  18. 18

    Cannot generate foreign key field in Django

  19. 19

    Limit choices and validate django's foreign key to related objects (also in REST)

  20. 20

    Django - Validate a disabled field in modelform_factory

  21. 21

    Modelform prepopulate foreign key

  22. 22

    Updating foreign key field in Django

  23. 23

    Django filter form field by Foreign Key

  24. 24

    Displaying foreign key attributes in ModelForm Django

  25. 25

    Django restframework: Validate a related field with a list of IDs

  26. 26

    iterate through certain number of foreign key objects

  27. 27

    Django Form with Foreign Key Related Data

  28. 28

    Autoincrement-like field for objects with the same foreign key (Django 1.8, MySQL 5.5)

  29. 29

    how to filter a model objects by related table's foreign key in django REST

HotTag

Archive