gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 21:55:15 26 4
gpt4 key购买 nike

我看过文档 here和几个类似的堆栈溢出帖子,但在保存我的表单后,我仍然无法返回该新模型的 ID/PK。它一直告诉我 'ProposalForm' 对象没有属性 'id'如何在保存后立即返回 ID?

这是 View :

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

最佳答案

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

关于python - 保存到 Django 中的模型后返回主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22976662/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com