问题
I am trying to initialize a Django formset with an addition parameter to pass on the forms in the formset. However when i initialize the formset with formset factory and pass the variable to it. the Kwargs is always empty
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)
The "print kwargs" always returns and empty dict {} and the kwargs.pop always goes into default. Am i doing something wrong?
回答1:
No, you don't. The parameters you pass are not named parameters, and are therefore stored in the *args
pointer. To get them into the **kwargs
dict you'd have to do this
formset = CIFormSet(data=data,grn_id=grn_id)
来源:https://stackoverflow.com/questions/23893696/django-formset-empty-kwargs