Reputation: 13
First of all english isn't my main language so please don't yell on me ;)
I have model with ManyToManyField. And I made for this form, but i can't add new items with this form. My kode looks like that:
forms.py
class NoteForm(forms.Form):
title = forms.CharField(max_length = 100)
author = forms.CharField(max_length = 100)
description = forms.TexField()
type = forms.CharField(max_length = 10)
disciple = forms.ManyToManyField(queryset=Disciple.objects.all())
views.py
def new_note(request):
note = Diary.objects.all()
disc = Disciple.objects.all()
form = NoteForm(request.POST)
if form.is_valid():
note_form = form.save(commit=False)
data = request.POST.copy()
note_form.title = form.cleaned_data['title']
note_form.author = form.cleaned_data['author']
note_form.description = form.cleaned_data['description']
note_form.type = form.cleaned_data['type']
note_form.disciple = form.cleaned_data['disciple']
for item in note_form.disciple:
note_form.disciple.add(item)
note_form.save()
form = NoteForm()
return render_to_response('dziennik/users.html', {'note': note, 'form': form},
context_instance=RequestContext(request))
else:
return render_to_response('dziennik/new_note.html', {'note': note, 'form': form},
context_instance=RequestContext(request))
And when im trying to add new object im getting error in this line:
note_form.disciple = form.cleaned_data['disciple']
And the error is:
"Diary: Diary object" needs to have a value for field "diary" before this many-to-many relationship can be used.
I don't know how to fix it and i can't go further without it.
Upvotes: 1
Views: 146
Reputation: 39699
You need to call note_form.save()
before adding ManyToMany
objects not after.
note_form.save()
for item in note_form.disciple:
note_form.disciple.add(item)
Upvotes: 1