0

The formset pass the is_valid() verification but {{ formset.errors }} returns [{}, {}, {}, {}] in template. (One {} for each form in the modelformset_factory formset.

I dont understand that the form is saved successfully anyway...

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))

form:

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']
4

1 回答 1

3

formset.errors是一个列表,其条目对应于其形式。当表单集有效时,单个表单上没有错误,因此formset.errors是一个空字典列表。

这意味着即使表单集有效,formset.errors也会评估为,因为非空列表总是评估为。另一个问题是返回表单集中的表单数量,而不是错误数量。在 Django 1.6 中有一种新方法可以解决这个问题。TrueTruelen(formset.errors)formset.total_error_count()

请注意,还有一个formset.non_form_errors()方法,它返回与任何特定表单无关的错误。

有关更多信息,请参阅有关表单集验证的文档。

于 2013-08-19T17:40:31.647 回答