Updating foreign key field in Django
I have a form displaying a dropdown for a foreignkey field. The form saves the users' selections, however I want the view to update the database record instead of inserting a new one. What's the best way to do this?
Current function:
def formset_valid(self, formset):
self.object = formset.save()
self.object.save()
return HttpResponseRedirect(self.get_success_url())
I've tried something like this:
d = RevisionDefaultType.objects.get(id=1) n = RevisionSettings.objects.get(self.object) d.defaultrevisiontype = n d.save()
But it throws an error that the data being updated is not an instance.
+3
source to share
2 answers
I was able to customize the update example from https://docs.djangoproject.com/en/dev/topics/db/queries/#saving-foreignkey-and-manytomanyfield-fields . This seems to work 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
revdefault.save()
return HttpResponseRedirect(self.get_success_url())
Thanks again for your help.
+1
source to share