在django中,提交新表单时,如何重定向到提交?

时间:2015-07-09 16:25:38

标签: python django forms

表单提交博客文章并在提交时重定向到索引页面。

如何更改它以便重定向到新提交的博客帖子

views.py

def post(request, post_url):
    single_post = get_object_or_404(Post, title=post_url.replace('_', ' '))
    popular_posts = Post.objects.order_by('-views')[:5]
    single_post.views+=1
    single_post.save()
    t=loader.get_template('blog/post.html')
    c = Context({'single_post': single_post, "popular_posts":popular_posts, })
    return HttpResponse(t.render(c))

def add_post(request):
context = RequestContext(request)
if request.method =='POST':
    form = PostForm(request.POST, request.FILES)
    if form.is_valid():
        form.save(commit=True)
        return redirect(index)
    else:
        print form.errors
else:
    form = PostForm()
return render_to_response('blog/add_post.html', {'form':form}, context)

2 个答案:

答案 0 :(得分:0)

检查django模型对象的get_absolute_url方法

def add_post(request):
    context = RequestContext(request)
    if request.method =='POST':
        form = PostForm(request.POST, request.FILES)
        if form.is_valid():
            form.save(commit=True)
            return redirect(form.instance.get_absolute_url())
        else:
            print form.errors
    else:
        form = PostForm()

     return render_to_response('blog/add_post.html', {'form':form}, context)

答案 1 :(得分:0)

考虑到您的博客文章网址为:

url(r'^blog/(?P<blog_id>[0-9]{4})/$', views.blog_detail, name='blog_detail'),

然后,

 def add_post(request):
    context = RequestContext(request)
    if request.method =='POST':
        form = PostForm(request.POST, request.FILES)
        if form.is_valid():
            obj = form.save(commit=True)
            return HttpResponseRedirect(reverse('blog_detail', obj.id))
        else:
            print form.errors
    else:
        form = PostForm()
    return render_to_response('blog/add_post.html', {'form':form}, context)