我在Django中有一个ModelFormset。
在模板中,我遍历表单,然后遍历表单中的每个字段(我将它用于两个不同的模型)。
{%for form in formset %}
<tr class='row{% cycle '2' '1' %}'>
{% for hiddenfield in form.hidden_fields%}
{{ hiddenfield }}
{% endfor %}
{% for field in form.visible_fields %}
<td>{{ field.errors}}{{ field }}</td>
{% endfor %}
</tr>
{% endfor%}
我已将can_delete = True添加到formset_factory,现在我在最右边找到了删除复选框。
有没有办法把它放在左边,仍像以前一样遍历其他表格字段?当我遍历字段时,有没有办法让它成为第一个表单字段?
答案 0 :(得分:3)
您可以覆盖BaseFormSet的add_fields方法,将删除字段移到前面,如下所示:
from collections import OrderedDict
from django import forms
from django.forms.formsets import BaseFormSet, formset_factory
from .models import MyModel
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
class BaseMyModelFormSet(BaseFormSet):
def add_fields(self, form, index):
super(BaseMyModelFormSet, self).add_fields(form, index)
# Pop the delete field out of the OrderedDict
delete_field = form.fields.pop('DELETE')
# Add it at the start
form.fields = OrderedDict(
[('DELETE', delete_field)] + form.fields.items())
MyModelFormSet = formset_factory(MyModelForm, BaseMyModelFormSet,
extra=2, can_delete=True)
答案 1 :(得分:0)
我一直得到“TypeError:只能连接列表(不是”ItemsView“)列出”上面的seddonym的建议代码。在Python 3中,有一种更简单的move an item in OrderedDict to the front方式。所以下面的代码为我完成了这项工作:
class BaseMyModelFormSet(BaseFormSet):
def add_fields(self, form, index):
super(BaseMyModelFormSet, self).add_fields(form, index)
# Move the delete field to the front end
form.fields.move_to_end('DELETE', last=False)