Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Inline field values based on parent instance

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?

like image 587
Hanpan Avatar asked Oct 29 '13 17:10

Hanpan


1 Answers

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)

like image 65
nkhumphreys Avatar answered Nov 01 '22 05:11

nkhumphreys