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?

2
  • 4
    Did you try this? stackoverflow.com/questions/1824267/… Commented Oct 29, 2013 at 20:17
  • 1
    I do this regularly. Use _construct_form instead of get_form. Commented Jun 24, 2014 at 16:54

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.