Search code examples
django-modelsdjango-formsdjango-viewsmany-to-manymanytomanyfield

Django - Save an object's m2m relationships to another object


I have a Temporaryresponse model, for survey responses. When the user saves answers on the final page of the survey to the Temporaryresponse object, I want to also save everything from that object to a new Completedresponse object. Everything is working EXCEPT I can't seem to save all of the m2m objects saved to a "race" field in the Temporaryresponse object to the "race" field in the Completedresponse object.

No matter what I try with add or set I can't figure out the correct way to do this.

P.S. - I really just want to save every single field from this Temporaryresponse object to the new Completedresponse object. Right now I'm doing this by manually saving each field (see zip_code...). Is there a way to just save everything at once?

views.py

def vr(request, pk):
    finalresponse = get_object_or_404(Temporaryresponse, pk=pk)
    instance = Temporaryresponse.objects.get(pk=pk)
    if request.method == "POST":
        form = VotingresponseForm(request.POST, instance=instance)
        if form.is_valid():
            votingresponse = form.save()
            votingresponse.save()
            completed_response = Completedresponse(zip_code=votingresponse.zip_code,...)
            completed_response.save()
            completed_response.race.add(votingresponse.race)
            completed_response.save()
            return redirect('completed')

Solution

  • Thanks. I am new to coding and need to get up and running quickly, so I'm using this as a prelim security boost as I continue to learn.

    I figured out the correct way to do this:

        if form.is_valid() and instance.ip == ip:
            votingresponse = form.save()
            votingresponse.save()
            completed_response = Completedresponse(zip_code=votingresponse.zip_coded...)
            completed_response.save()
            completed_response.race.set(votingresponse.race.all())
            completed_response.save()
            votingresponse.delete()