我已经看过文档here和几个类似的堆叠溢出帖子,但在保存表单之后我还是无法返回该新模型的ID / PK。它一直告诉我'ProposalForm' object has no attribute 'id'
如何在保存后立即返回ID?
这是观点:
def proposal_create_view2(request):
if request.method == 'POST':
form = ProposalForm(data=request.POST)
if form.is_valid():
form.save()
response = {}
response['proposalID'] = form.id
return response
答案 0 :(得分:4)
my_saved_model = my_model_form.save()
打印my_saved_model.pk
修改强>
def proposal_create_view2(request):
if request.method == 'POST':
form = ProposalForm(data=request.POST)
if form.is_valid():
mysaved_model = form.save()
response = {}
response['proposalID'] = mysaved_model.id #or .pk
return render(request , 'my_template_file.html' , response)
#return response statement is NOT valid as you need to return an HttpResponse not a dict
答案 1 :(得分:1)
ModelForm.save()
的返回值是新模型。取而代之的是PK。