【问题标题】:How to pass extra kwargs to form in django modelformset factory?如何在 django modelformset factory 中传递额外的 kwargs 来形成?
【发布时间】:2020-05-06 16:51:23
【问题描述】:

如何在modelformset工厂中将额外的kwargs传递给django modelform

例如,我想禁用详细视图中的所有表单字段。

forms.py:

class ConceptForm(forms.ModelForm):

  class Meta:
    model = app_models.Concept
    fields = '__all__'

  def __init__(self, *args, **kwargs):

    self.action = kwargs.pop('action', None)

    super(ConceptForm, self).__init__(*args, **kwargs)

    if self.action is not None:
      if self.action == 'detail':
        for field in self.fields:
          self.fields[field].widget.attrs['readonly'] = True

views.py

modelformset = modelformset_factory(
  model = model,
  fields = show_fields,
  form = ConceptForm(kwargs={'action': 'detail'), <-- I would like something like this
)

错误是:

“ConceptForm”对象不可调用

没有调用 init 不会显示错误,但表单字段不会被禁用

modelformset = modelformset_factory(
  model = model,
  fields = show_fields,
  form = ConceptForm
)

提前致谢

【问题讨论】:

    标签: django django-forms


    【解决方案1】:

    正如Passing custom parameters to formset forms section of the documentation 中指定的那样,您可以使用FormSetform_kwargs=… 参数:

    ConceptFormSet = modelformset_factory(
        model = Concept,
        form = ConceptForm,
        fields = show_fields
    )
    formset = ConceptFormSet(form_kwargs={'action': 'detail'})

    【讨论】:

      猜你喜欢
      • 2018-06-16
      • 2018-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-16
      • 1970-01-01
      相关资源
      最近更新 更多