How to get the ID of the current form submission in Django

What if you need the ID of the model of the submitted form? How do you get the ID of the current form submission in Django?

Maybe you tried getting it from the request object or probably queried it in the DB but all you’re getting are null errors.

You can get the ID of the saved form or model via the returned object of the save method.

Let’s say you have a Task model and want its ID. You are also using model forms. Here’s how to get it:

def new(request):
	if request.method == 'POST':
		form = TaskForm(request.POST)
		if form.is_valid():
			task = form.save()

			# You can now get the ID via task.id

			return redirect('details', pk=task.id)
		else:
			form = TaskForm()
	return render(request, 'task/new.html', {'form': form})

This also works if you are using a regular Django model. Just remember that by calling save(), it saves the model and returns a populated object which includes the ID.


Do you want more Python and Django tips and tutorials? Drop your email in the box below and we'll send new content straight to your inbox.

Leave a Comment