首先,英语不是我的主要语言,所以请不要对我大喊;)
我有ManyToManyField的模型。我为这个表单做了,但我不能用这个表单添加新项目。我的kode看起来像那样:
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))
当我尝试添加新对象时,我会在此行中收到错误:
note_form.disciple = form.cleaned_data ['disciple']
错误是:
"Diary: Diary object" needs to have a value for field "diary" before this many-to-many relationship can be used.
我不知道如何解决这个问题,如果没有它我就无法继续下去。
答案 0 :(得分:1)
在添加note_form.save()
对象之前,您需要先致电ManyToMany
。
note_form.save()
for item in note_form.disciple:
note_form.disciple.add(item)