0
我目前正在嘗試渲染一個表單,該表單將允許我們的用戶編輯產品,當前表單正在全部顯示爲一個長列。迭代構建脆皮形式佈局?
已要求我把它分成兩列,但我有利用所產生因ModelForm
問題modelform_factory()
有什麼辦法中,我可以生成插入新的每一個DIV酥脆佈局對象兩個表單對象?
注意:表格的長度事先不知道。
查看代碼:
def layout_from_form(form, columns=2):
field_count = sum(1 for i in form) # form specified it's iterable but is not len() friendly
for field_number, _ in enumerate(form):
if field_number % columns == 0:
max_length_field = field_number + 2
if field_number + 2 > field_count:
max_length_field = field_count
try:
selected_forms = form.helper[field_number:max_length_field]
selected_forms.wrap(Div, css_class="span6")
selected_forms.wrap_together(Div, css_class="row-fluid")
except:
assert False, (field_count, field_number, max_length_field)
def edit_product(request, bought_in_control_panel_id, item_uuid):
boughtin_model = get_model_for_bought_in_control_panel(bought_in_control_panel_id)
item = boughtin_model.objects.get(pk=item_uuid)
BoughtinForm = modelform_factory(boughtin_model, exclude=("uuid", "date_time_updated", "date_time_created",
"manufacturer"))
if request.method == "POST":
boughtin_form = BoughtinForm(request.POST, instance=item)
if boughtin_form.is_valid():
boughtin_form.save()
return redirect(reverse('view_product', kwargs={'bought_in_control_panel_id': bought_in_control_panel_id,
'item_uuid': item_uuid}))
else:
boughtin_form = BoughtinForm(instance=item)
boughtin_form.helper = FormHelper(boughtin_form)
boughtin_form.helper.form_action = reverse('edit_product', kwargs={'bought_in_control_panel_id': bought_in_control_panel_id,
'item_uuid': item_uuid})
boughtin_form.helper.add_input(Submit('submit', 'Submit'))
layout_from_form(boughtin_form)
return render_to_response('suppliers/products/edit_product.html', {'item': item,
'boughtin_form': boughtin_form,
'bought_in_control_panel_id': bought_in_control_panel_id})
實例佈局對象:
Layout(
Div(
Field('name'),
Field('type'),
css_class="row-fluid"
),
Div(
Field('uuid'),
Field('dave'),
css_class="row-fluid"
),
.... Etc ad infinitum ....
)
事先不知道表單的長度是什麼? –
您是否看到過使用酥脆形式的文檔「更新佈局」:http://django-crispy-forms.readthedocs.org/en/latest/dynamic_layouts.html特別是,[wrap](http: //django-crispy-forms.readthedocs.org/en/latest/dynamic_layouts.html#wrap)操作可能正是你正在尋找的。 感覺你可以在視圖中確定傳入表單(可變長度)的長度,並以此方式創建動態佈局。 –
好吧,我不知道如何獲得由modelform_factory生成的表單上的字段數,並且我不能依賴每次傳遞的相同模型。 – Jharwood