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
- [Django]-Deploy Django\Tornado on Heroku
- [Django]-Django distinct on case sensitive entries
- [Django]-How much dog food should one eat? β Internal and External RestAPI & Oauth2
- [Django]-Serve static files with Django both from CDN and local directories
- [Django]-How to send the javascript list of dictionaries object to django ajax
Source:stackexchange.com