2

Let's say I submit a form to the back-end and I save a record of the model in the following way:

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__'

Right after saving the form, I would like to get the id of the record for the model.

I tried with form.id and form.pk as I saw in other similar questions without success.

How can I get the id or the pk of the new entry added to the Project model?

Cheknov
  • 1,892
  • 6
  • 28
  • 55

1 Answers1

1

form.save() returns the object, so:

obj = form.save()
print(obj.pk)
Brian Destura
  • 11,487
  • 3
  • 18
  • 34