[Django]-How to redirect to a newly created object in Django without a Generic View's post_save_redirect argument

6👍

A ModelForm‘s save method returns the newly created model instance. In your case, this means you should be able to work with the following:

if form.is_valid():
    story = form.save()
    return HttpResponseRedirect(reverse('story_detail', args=(story.user, story.id)))

3👍

Using the reverse and redirect

from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.urls import reverse

# inside def
  if form.is_valid():
    story = form.save()
    messages.success(request, 'Story created successfully!')

    return redirect(reverse('story_detail', kwargs={'story':story.id}))
👤Kermit

1👍

Adding to the other answers, you can now just call redirect to an object, which is going to look for the get_absolute_url method of it. So if you have that set, just write:

return redirect(obj)
👤martin

Leave a comment