Please refer this link for trace back
2。即使我在forms.py中更改了标签名称,它也使用了我尝试使用的默认名称,该代码可以解决该问题,但尚未解决。name = forms.CharField(label='Singer')
class AlbumForm(forms.ModelForm):
title = forms.CharField(max_length=50,label='Album title')
class Meta:
model=Album
exclude = ['singer']
class SingerForm(forms.ModelForm):
class Meta:
model = Singer
fields = ['name']
label = {'name':'Singer'}
class AlbumSinger(View):
def get(self,request,pk=None):
singer_form = SingerForm(instance=Singer())
album_form = AlbumForm(instance=Album())
context = {
'singer_form':singer_form,
'album_form':album_form
}
return render(request, 'album/multi_form.html', context)
def post(self,request,pk=None):
context = {}
singer_form = SingerForm(request.POST,instance=Singer())
album_form = AlbumForm(request.POST,instance=Album())
if singer_form.is_valid and album_form.is_valid:
singer_form.save()
new_album = album_form.save(commit=False)
new_album.singer = singer_form
new_album.save()
return HttpResponseRedirect('/album/')
context = {
'singer_form' : singer_form,
'album_form' : album_form
}
return render(request, 'album/multi_form.html', context)
答案 0 :(得分:1)
尝试一下
if singer_form.is_valid and album_form.is_valid:
singer_instance = singer_form.save() # assign the created instance to a variable
new_album = album_form.save(commit=False)
new_album.singer = singer_instance # use the model instance
new_album.save()