Django formset - 空的kwargs

时间:2014-05-27 15:45:43

标签: python django formset kwargs

我正在尝试使用add参数初始化一个Django formset,以传递formset中的表单。但是当我使用formset工厂初始化formset并将变量传递给它时。 Kwargs永远是空的

forms.py

from django.forms.formsets import BaseFormSet
from django.forms.formsets import formset_factory

class BaseCIFormSet(BaseFormSet):

    def __init__(self, *args, **kwargs):
        print kwargs
        self.grn_id = kwargs.pop('grn_id', None)
        super(BaseCIFormSet, self).__init__(*args, **kwargs)

    def _construct_forms(self):
        self.forms = []
        for i in xrange(self.total_form_count()):
            self.forms.append(self._construct_form(i, grn_id=self.grn_id))

Views.py

data['form-TOTAL_FORMS'] = count
data['form-INITIAL_FORMS'] = count
data['form-MAX_NUM_FORMS'] = ''

CIFormSet = formset_factory(CIForm, formset=BaseCIFormSet, extra=(count), can_delete=True)
formset = CIFormSet(data, grn_id)

“print kwargs”总是返回并清空dict {},并且kwargs.pop总是进入默认状态。我做错了吗?

1 个答案:

答案 0 :(得分:1)

不,你没有。您传递的参数不是命名参数,因此存储在*args指针中。要让他们进入**kwargs dict,你必须这样做

formset = CIFormSet(data=data,grn_id=grn_id)