我有一个表单(正常工作),我想传递给Formset,但是传递给ChoiceFields的元组不会呈现或出错:
这是原始形式:
class PO_Form(forms.Form):
def __init__(self, baseItem_choices, color_choices, material_choices, sizeGroup_choices, *args, **kwargs):
super(PO_Form, self).__init__(*args, **kwargs)
self.fields['base_item'].choices = baseItem_choices
self.fields['color_or_print'].choices = color_choices
self.fields['material'].choices = material_choices
self.fields['size_group'].choices = sizeGroup_choices
base_item = forms.ChoiceField(choices=(), required=True)
color_or_print = forms.ChoiceField(choices=(), required=True)
material = forms.ChoiceField(choices=(), required=True)
size_group = forms.ChoiceField(choices=(), required=True)
这个形式ChoiceFields是从我在视图中创建的各种操作列表中填充的:
form = PO_Form(baseItem_choices, color_choices, material_choices, sizeGroup_choices)
我如何在formset中完成这项工作?我尝试了两种方法: 1:
PO_FormSet = formset_factory(PO_Form(baseItem_choices, color_choices, material_choices, sizeGroup_choices), extra=2)
我收到此错误:
文件 " /Library/Python/2.7/site-packages/django/core/handlers/exception.py" 在内心 39. response = get_response(request)
File" /Library/Python/2.7/site-packages/django/core/handlers/base.py" 在_get_response中 187. response = self.process_exception_by_middleware(e,request)
File" /Library/Python/2.7/site-packages/django/core/handlers/base.py" 在_get_response中 185. response = wrapped_callback(request,* callback_args,** callback_kwargs)
文件" / Users / carlospceballos / Dropbox (个人)/django/projectos/WholeSale/ShowRoom/views.py"在 PO_formset_populate 115. PO_FormSet = formset_factory(PO_Form(baseItem_choices,color_choices,material_choices,sizeGroup_choices),extra = 2)
File" /Library/Python/2.7/site-packages/django/forms/formsets.py"在 formset_factory 449.返回类型(表单。名称 + str(' FormSet'),(formset,),attrs)
异常类型:/ showroom / po_populate / 3 / Exception中的AttributeError 价值:' PO_Form'对象没有属性' 名称'
2:我尝试在视图中设置初始值:
PO_FormSet = formset_factory(PO_Form(), extra=2)
formset = PO_FormSet(initial=[
{ 'base_item': baseItem_choices,
'color_or_print': color_choices,
'material': material_choices,
'size_group': sizeGroup_choices, }
])
如果我没有修改PO_Form,则会出现错误,表示该表单需要5个参数而我只能通过1.如果我修改表单(剥去 init ),我就不会出错但是选择领域是空的......我做错了什么?
答案 0 :(得分:1)
您正在将表单实例而不是表单类传递给formset_factory
方法。您可以在实例化formset后设置选项。
forms.py:
class PO_Form(forms.Form):
base_item = forms.ChoiceField(choices=(), required=True)
color_or_print = forms.ChoiceField(choices=(), required=True)
material = forms.ChoiceField(choices=(), required=True)
size_group = forms.ChoiceField(choices=(), required=True)
views.py:
PO_FormSet = formset_factory(PO_Form)
formset = PO_FormSet()
for form in formset.forms:
form.fields['base_item'].choices = baseItem_choices
form.fields['color_or_print'].choices = color_choices
form.fields['material'].choices = material_choices
form.fields['size_group'].choices = sizeGroup_choices