Formset创建新条目而不是更新

时间:2010-07-27 00:45:26

标签: django django-models django-forms

我在视图中有以下代码:

def controller_details(request, object_id):
    controller = Controller.objects.get(pk=object_id)
    controllerURI = controller.protocol + '://' + controller.server + '/' + controller.name

    FilterFormSet = inlineformset_factory(Controller, Filter, extra=2)

    if request.method == 'POST':
        formset  = FilterFormSet(request.POST, request.FILES, instance=controller)
        if formset.is_valid():
            formset.save()
        else:
            HttpResponseRedirect('controller-details')
    else:
        formset = FilterFormSet(instance=controller)

    return render_to_response('controller_details.html', {'formset':formset, 'controllerURI':controllerURI}, context_instance=RequestContext(request))

在我的模型中,单个控制器由多个过滤器(一对多)组成,每个过滤器可以将另一个过滤器作为其输出的目标(自我一对多)。当我尝试更新特定过滤器的目标时,不是更新目标值,而是获得一个全新的条目。以下是该模型的部分内容:

class Filter(Component):
controller  = models.ForeignKey(Controller)
targetURI   = models.ForeignKey('self', verbose_name='Target URI', null=True, blank=True)
filterType  = models.CharField('Type', max_length=64, choices=FILTER_TYPES,)
firstFilter = models.BooleanField('First Filter')

提前致谢。

1 个答案:

答案 0 :(得分:1)

终于明白了。对于那些可能存在类似问题的解决方案如下:

controller = Controller.objects.get(pk=object_id)
controllerURI = controller.protocol + '://' + controller.server + '/' + controller.name
FilterFormSet = inlineformset_factory(Controller, Filter, extra=5)

if request.method == 'POST':
    formset  = FilterFormSet(request.POST, request.FILES, instance=controller)

    if formset.is_valid():
        instances = formset.save(commit=False)

        for instance in instances:
            instance.save()

formset = FilterFormSet(instance=controller)

return render_to_response('controller_details.html', {'formset':formset, 'controllerURI':controllerURI}, context_instance=RequestContext(request))