开发者

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

I'm trying to redirect a user to a newly creat开发者_运维知识库ed object's object.get_absolute_url() after saving a form. I'm not using a generic view, so I can't use the post_save_redirect argument. The relevant portion of the view is like so:

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

Now how would I get at the story object between the form.save() and the HttpResponseRedirect so that I can do the reverse lookup?


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)))


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}))


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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜