【问题标题】:How to get the ID of the record created in the model after saving it from a Form从表单保存后如何获取模型中创建的记录的ID
【发布时间】:2022-01-05 03:37:38
【问题描述】:

假设我向后端提交了一个表单,并通过以下方式保存了模型的记录:

views.py:

def viewName(request):
    if request.method == 'POST':
        form = ProjectForm(request.POST)
        if form.is_valid():
            form.save() #I want to get the id of this after it is saved
        else:
            print (form.errors)
            form = ProjectForm()
    return render(request, 'index.html', context)

forms.py:

class ProjectForm(ModelForm):
    class Meta:
        model = Project
        fields = '__all__'

保存表单后,我想获取模型记录的 id。

我尝试使用 form.idform.pk,正如我在其他类似问题中看到的那样,但没有成功。

如何获取添加到Project 模型的新条目的idpk

【问题讨论】:

    标签: django django-models django-views django-forms


    【解决方案1】:

    form.save() 返回对象,所以:

    obj = form.save()
    print(obj.pk)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多