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:
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?
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