0

I have a Django form called MyDjangoModelForm. In which, I have overridden the init() function to make changes to the form based on the model. It looks like this:

def __init(self, *args, **kwargs)__:
    super(MyDjangoModelForm, self).__init__(*args, **kwargs)

    instance = getattr(self, 'instance', None)
    if instance and instance.pk:
        choice_items = models.MyChoiceItems.objects.filter(myfield=instance.myfield)

    self.fields['choice_field'].widget.choices = [(choiceitem.id, choiceitem) for item in choice_items]

This works perfectly on my initial inline form. However when I click Add Another Inline Form the entries it creates does not have the choices filter applied.

How can I apply this filter to the form that's added when I click Add another... ?

LondonAppDev
  • 8,501
  • 8
  • 60
  • 87
  • If you click 'Add another', then it is a new instance without a pk. It's not clear what you want the choices to be in that case, since `instance.myfield` will not be set yet. – Alasdair Aug 27 '15 at 08:58
  • Yeah I know, but I'm wondering if there is any way to give it context of the pk? Since it's an inline can I access the data about the model in the parent form? – LondonAppDev Aug 27 '15 at 09:00
  • 1
    It should be possible to pass the parent object to the inline's model form, but I'm not sure which methods you'll have to override. You could start looking at [`get_formsets_with_inlines`](https://docs.djangoproject.com/en/1.8/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_formsets_with_inlines). [This similar question](http://stackoverflow.com/questions/32150088/django-access-the-parent-instance-from-the-inline-model-admin) earlier this week never got an answer. – Alasdair Aug 27 '15 at 09:16

0 Answers0