django - 如何通过额外的 kwargs 在 django 模型集工厂中形成?

标签 django django-forms

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

例如,我想在详细 View 中禁用所有表单字段。

表格.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

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

错误是:

'ConceptForm' object is not callable



没有调用 init 未显示错误,但未禁用表单字段
modelformset = modelformset_factory(
  model = model,
  fields = show_fields,
  form = ConceptForm
)

提前致谢

最佳答案

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

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

关于django - 如何通过额外的 kwargs 在 django 模型集工厂中形成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59827348/

相关文章:

javascript - Django Angular 数据库集成

python - 如何检测 obj 是否在 ModelForm.clean 中添加或编辑?

python - 如何重写模型的保存方法来更改文件字段名称?

python - 在 Django 模型中存储电话号码的最佳方式是什么?

python - 无法导入设置。不支持按名称导入

CreateView 后 django 重定向到以前的 url

Django:Django 管理中具有唯一外键的用户配置文件

django - 将 django 表单中的 bool 模型字段显示为单选按钮而不是默认复选框

django - Django管理员内联中的“国家/州/城市”下拉菜单

django - 如何在 Django Rest Framework 中记录 4XX Http 状态的请求和响应?