0

I'm having some difficulties with Django's ModelChoiceField.

I wrote the following code:

class BookForm(ModelForm):
    publisher = forms.ModelChoiceField(queryset=Publisher.objects.all())
    ...

Now Book and Publisher are related this way: Book → Library → SubPublisher → Publisher. All relations were made using ForeignKey.

My form is like that:

  • Publisher (ModelChoiceField)
  • SubPublisher (ModelChoiceField with autocomplete widget that filters according to Publisher selection)
  • Library (same as SubPublisher, filters according to SubPublisher)

My problem is that I can't get ModelChoiceField to select the relevant Publisher out of the publishers list.

Note: Publisher & SubPublisher are only there to filter on Libraries - and it works, the issue is only about setting initial values according to selected Library's ForeignKeys.

What am I missing?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Yuval
  • 31
  • 4
  • add -- publisher = forms.ModelChoiceField(queryset=Publisher.objects.all(), initial='1') – Marin Sep 03 '18 at 11:48
  • thx but that will get me the item which pk=1, which is not my intention. I would like to have selected the publisher that belongs to the selected sub-publisher – Yuval Sep 03 '18 at 12:02

1 Answers1

1

I figured it out. Publishing so it will be helpful for others.

Override ModelForm init function like so:

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if kwargs['instance']:
            model_instance = kwargs['instance']

Then, use the id(s) fetched from the model instance to override the initial data of the ModelForm fields, here is for the example in the question:

            if hasattr(model_instance, 'library') \
                and hasattr(model_instance.library, 'subpublisher_id'):
            subpublisher_id = model_instance.library.subpublisher_id
            self.fields['subpublisher'].initial = subpublisher_id
            if hasattr(model_instance.library, 'subpublisher') \
                    and hasattr(model_instance.library.subpublisher, 'publisher_id'):
                publisher_id = str(model_instance.library.subpublisher_id.publisher_id)
                self.fields['publisher'].initial = publisher_id
Yuval
  • 31
  • 4