formset传递is_valid()
验证,但{{ formset.errors }}
在模板中返回[{}, {}, {}, {}]
。 (对于modelformset_factory formset中的每个表单,只有一个{}。
我不明白表格是否已成功保存......
def setMapOptions(request, map_name):
map_selected = EzMap.objects.get(map_name=map_name, created_by=request.user)
layers_ordered = LayerMapOptions.objects.filter(ezmap=map_selected).order_by('position')
layerForm = modelformset_factory(LayerMapOptions, form=LayerMapOptionsForm, extra=0)
if request.POST:
pk_list = [int(x) for x in request.POST.get("layersOrder").split(',')]
formset = layerForm(request.POST, queryset=layers_ordered)
if formset.is_valid():
for form in formset:
instance = form.instance
instance.position = pk_list.index(instance.pk)
instance.save()
else:
formset = ezMapOptionFormSet(user=request.user, instance=map_selected)
formset2 = layerForm(queryset=layers_ordered)
tmsURL = "http://" + request.get_host() + "/ezmapping/tms/"
return render_to_response("ezmapping/manage_map_Options.html", {'formset': formset, 'map': map_selected, 'layersOrder': layers_ordered, 'tmsURL' : tmsURL, }, context_instance=RequestContext(request))
形式:
class ModelLinkWidget(forms.Widget):
def __init__(self, obj, attrs=None):
self.object = obj
super(ModelLinkWidget, self).__init__(attrs)
def render(self, name, value, attrs=None):
if self.object.pk:
return mark_safe(
u'<a href="/ezmapping/layer/edit/%s">%s</a>' %\
(
self.object.pk, self.object
)
)
else:
return mark_safe(u'')
class LayerMapOptionsForm(ModelForm):
link = forms.CharField(label='link', required=False)
def __init__(self, *args, **kwargs):
super(LayerMapOptionsForm, self).__init__(*args, **kwargs)
self.fields['link'].widget = ModelLinkWidget(self.instance.layer)
class Meta:
model = LayerMapOptions
fields = ['link', 'visible']
答案 0 :(得分:3)
formset.errors
是一个列表,其条目对应于其表单。当formset有效时,各个表单上没有错误,因此formset.errors
是一个空字典列表。
这意味着即使表单集有效,formset.errors
也会评估为True
,因为非空列表始终计算为True
。另一个问题是len(formset.errors)
返回表单集中的表单数,而不是错误数。在Django 1.6中,有一种新的formset.total_error_count()
方法可以解决这个问题。
请注意,还有一个formset.non_form_errors()
方法,它返回与任何特定表单无关的错误。
有关详细信息,请参阅formset validation上的文档。