[Django]-Save ManyToMany with through intermediary class

4πŸ‘

βœ…

The solution for save a ManyToMany relation with a intermediary class (through):

def add_setor(request):
    form = SetorForm(request.POST or None)
    if form.is_valid():     
        setor = Setor.objects.create(nome=form.cleaned_data['nome'])
        for promotor_id in request.POST.getlist('promotores'):   
            m1 = Membro(promotor_id=promotor_id, setor=setor)
            m1.save()
        messages.add_message(request, messages.SUCCESS, 'Setor cadastrado com sucesso!')
        return HttpResponseRedirect('/project/setor/index/')
    return render_to_response('project/setor/form.html', locals(), context_instance=RequestContext(request))

I have not use the form directly, but extract the setor name of the form then create the object setor. Create the Membro object with the id’s promotores in the form and the object setor, the last action is the save Membro object.
Regards.

πŸ‘€LinuxMan

4πŸ‘

You have promotores field in your form linked to the model so save() tries to save it to m2m field. You can save form with commit=False, then save object manually (it will not touch m2m) and then save m2m as you do now.

P.S. I guess you should use form.cleaned_data['promotores'] rather then request.POST. God knows what was actually POSTed from the client.

πŸ‘€ilvar

Leave a comment