Django -基于父实例的内联字段值

时间:2023-01-17 15:40:26

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?

也许我必须用另一种方法来处理,并从父节点中访问inlines ?

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?

以上这些有可能吗?

1 个解决方案

#1


1  

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

您可以使用get_form_kwargs方法,并将这些选项传递给form init方法

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)

您可以在get_form_kwargs方法中执行父对象检查,并传递一个不同的选择(我认为)

#1


1  

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

您可以使用get_form_kwargs方法,并将这些选项传递给form init方法

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)

您可以在get_form_kwargs方法中执行父对象检查,并传递一个不同的选择(我认为)