保存到Django中的模型后返回主键

时间:2014-04-10 00:50:14

标签: python django return

我已经看过文档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

2 个答案:

答案 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

审核Django Docs on HttpResponses

答案 1 :(得分:1)

ModelForm.save()的返回值是新模型。取而代之的是PK。