如何使用对象实例化FormSet

时间:2015-10-15 11:24:56

标签: python django

我尝试查看Django Docs,看看我是否可以在ModelForm中找到与实例类似的参数,但我无法使其正常工作。

class RequiredFormSet(BaseFormSet):
    def __init__(self, *args, **kwargs):
        super(RequiredFormSet, self).__init__(*args, **kwargs)
        for form in self.forms:
            form.empty_permitted = False

OfferItemFormSet = formset_factory(OfferItemForm, formset=RequiredFormSet)

Forms.py

class OfferItemForm(ModelForm):

class Meta:
    model = OfferItem
    exclude = ('offer', 'item_code', 'type')
    [...]

Views.py

i = OfferItem.objects.filter(offer=o).values()
item_formset = OfferItemFormSet(queryset=i)

我总是__init__() got an unexpected keyword argument 'queryset'。我试图从formset_factory更改为modelformset_factory但仍然是同样的问题。

Traceback:
File "/Library/Python/2.7/site-packages/Django-1.8.3-py2.7.egg/django/core/handlers/base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Library/Python/2.7/site-packages/Django-1.8.3-py2.7.egg/django/contrib/auth/decorators.py" in _wrapped_view
  22.                 return view_func(request, *args, **kwargs)
File "[...]/filter_decorators.py" in _wrapped_view
  13.                 return a_view(request, *args, **kwargs)
File "[...]/views.py" in manage_offer
  1330.         item_formset = OfferItemFormSet(queryset=i)
File "[...]/forms.py" in __init__
  197.             super(RequiredFormSet, self).__init__(*args, **kwargs)

Exception Type: TypeError at /my/offer/add/
Exception Value: __init__() got an unexpected keyword argument 'queryset'

为什么这么重要?为什么formset的构造函数方法上没有instance =参数,就像ModelForm一样?

编辑:使用modelformset_factory()

OfferItemFormSet = modelformset_factory(OfferItem, form=OfferItemForm, formset=RequiredFormSet)

Forms.py

from django.forms.models import modelformset_factory

class RequiredFormSet(BaseFormSet):
    def __init__(self, *args, **kwargs):
        super(RequiredFormSet, self).__init__(*args, **kwargs)
        for form in self.forms:
            form.empty_permitted = False

Views.py

i = OfferItem.objects.filter(offer=o)
item_formset = OfferItemFormSet(queryset=i)

__init__() got an unexpected keyword argument 'query set'
Exception Location: [...]/forms.py in __init__, line 198

分辨率

BaseFormSet更改为BaseModelFormSet并在模板中生成formset时将{{ form.id }}添加到我的循环中。

1 个答案:

答案 0 :(得分:3)

如果要使用模型对象,则需要使用ModelFormset和modelformset_factory