views:

16

answers:

1

I have the following code in a view:

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

In my model a single Controller is made up of multiple Filters (one to many) and each Filter can have another Filter as a target for its output (one to many on self). When I try to update the target for a particular Filter, instead of updating the target value I get an entire new entry. Here is what part of the model looks like:

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

Thanks in advance.

A: 

Finally figured it out. Solution below for those that may have similar problem:

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