我目前正在尝试渲染一个允许我们的用户编辑产品的表单,目前表单显示为一个长列。
我已要求将其拆分为两列,但由于使用ModelForm
modelform_factory()
而遇到问题
有没有什么方法可以生成一个Crispy布局对象,可以在每两个表单对象中插入新的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 ....
)
答案 0 :(得分:1)
在你的问题中:“注意:事先不知道表格的长度。”
我们确实可以事先找到表格的长度:
>>> import apps.students.models as models
>>> from django.forms.models import modelform_factory
>>> form = modelform_factory(models.StudentProfileBasics)
>>> len(form.base_fields.keys())
5
从那里,a)Crispy通过抓取布局切片的modify layouts on the go能力,b)Crispy提供的wrap方法,以及c)由forms.Form提供的列表的组合。 base_fields.keys()可以让你到达你需要的地方!