gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 10:43:25 25 4
gpt4 key购买 nike

我如何将额外的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com