11

I am trying to set the default values of a choice field on an inline based on the properties of the parent form / instance.

In pseudo code, it would look something like:

def get_form(self, ***):
   if self.parent.instance && self.parent.instance.field_x == "y":
      self.field_name.choices = ...

I've searched on Google but can't seem to find anything about referencing the parent form from within an inline.

Perhaps I have to do this the other way around, and access the inlines from within the parent?

def get_form(self, ***):
   if self.instance:
      for inline in self.inlines:
          if instanceof(inline, MyInline):
             inline.field_name.choices = ...

Are any of the above possible?

Mike Deluca
  • 1,295
  • 2
  • 18
  • 41
Hanpan
  • 10,013
  • 25
  • 77
  • 115

1 Answers1

1

You could use the get_form_kwargs method and pass the choices into the form init method like so

class Form(forms.Form):
    def __init__(self, *args, **kwargs):
        choices = kwargs.pop('choices', None)
        super(Form, self).__init__(*args, **kwargs)
        form.field.choices = choices

class FormView(generic.FormView):

    def get_form_kwargs(self, *args, **kwargs)
        kwargs = super(FormView, self).get_form_kwargs()
        kwargs['choices'] = choices
        return kwargs

you could do your parent object check in the get_form_kwargs method and pass in a different choice (I think)

nkhumphreys
  • 966
  • 7
  • 12