Karl Karl - 1 year ago 88
Python Question

Updating foreign key field in Django

I have a form that displays a drop down for a foreignkey field. The form saves the users selection, however I want the view to update the database entry rather than inserting a new one. Whats the best way to go about this?

Current function:

def formset_valid(self, formset):
self.object = formset.save()
return HttpResponseRedirect(self.get_success_url())

I have tried something like this:

d = RevisionDefaultType.objects.get(id=1)
n = RevisionSettings.objects.get(self.object)
d.defaultrevisiontype = n

But it throws an error that the data being updated is not an instance.

Answer Source

I managed to tweak the update example from https://docs.djangoproject.com/en/dev/topics/db/queries/#saving-foreignkey-and-manytomanyfield-fields. This seems to be working as desired.

    def formset_valid(self, formset):

        self.object = formset.save(commit=False)
        revdefault = RevisionDefaultType.objects.get(pk=1)
        revget = RevisionSettings.objects.get(global_revision_type=self.object)
        revdefault.defaultrevisiontype = revget

        return HttpResponseRedirect(self.get_success_url())

Thanks again for the help.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download