Django 将自定义表单参数传递给 modelformset_factory

2 投票
2 回答
2371 浏览
提问于 2025-04-18 11:52

根据这个关于formset_factory的回答,我尝试对modelformset_factory做同样的事情:

from django.utils.functional import curry
from functools wraps

AccountMemberFormSetBase = modelformset_factory(AccountMember,
                                                form=wraps(AccountMemberLimitedModelForm)(curry(AccountMemberLimitedModelForm, affiliate="test")),
                                                extra=2)

这段代码出现了以下错误:

function() argument 1 must be code, not str
Exception Location: ../django/forms/models.py in modelform_factory, line 528

你知道这里出什么问题了吗?

2 个回答

0
class AccountMemberLimitedModelForm(forms.Form):
...     def __init__(self, *args, **kwargs):
...         affiliate = kwargs.pop('affiliate')
...         super(AccountMemberLimitedModelForm, self).__init__(*args, **kwargs)



AccountMemberFormSetBase = formset_factory(AccountMemberLimitedModelForm)
    formset = AccountMemberFormSetBase(form_kwargs={'affiliate': "test"})

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

1

今天我也遇到了同样的问题。

你可以看看我在 Django 传递自定义表单参数到表单集 里的评论,里面有详细信息和解决办法(我希望链接到 StackOverflow 是可以的)。

撰写回答