如何在处理表单获取NoReverseMatch错误后重定向到不同的视图

时间:2011-12-07 20:16:40

标签: django redirect django-views

我正在创建一个博客应用程序,我想在处理完表单后重定向到另一个不同的URL,但下面给出的视图不起作用。我既不能使用HttpResponseRedirect也不能简单地重定向

@login_required
def blog_form(request,author_id=None,slug=None):

    context_instance=RequestContext(request)

    # This view will have a valid creator_id and slug field if the
    # blog is being edited and in this case the creator and user should be same
    if ( author_id and slug):
        author = User.objects.get(pk=author_id)
        blog = get_object_or_404(Entry, creator = author, slug = slug)
        if blog.creator != request.user:
            raise HttpResponseForbidden()

    # We set the user and created date and make a new object
    else:
        blog = Entry(creator=request.user,created_date=datetime.datetime.now() )

    if request.method == 'POST':

        #if the blog is not published
        if 'save' in request.POST:
            form = EntryForm(request.POST, instance = blog)
            if form.is_valid():
                form.save()

        elif 'publish' in request.POST:
            blog.pub_date = datetime.datetime.now()
            blog.status = 1
            form = EntryForm(request.POST, instance = blog)
            if form.is_valid():
                form.save()
                #return HttpResponseRedirect ('view_blog', (),{'author_id':blog.creator.id,'slug' :blog.slug,})
                return redirect ('blogs', blog.creator.id, blog.slug)
                #return render_to_response('blog/blog_view.html', {'blog': blog,},context_instance=RequestContext(request))

        elif 'preview' in request.POST: 
            form = EntryForm(request.POST, instance = blog)
            if form.is_valid():
                form.save()
                return render_to_response('blog/blog_view.html', {'blog': blog,},context_instance=RequestContext(request))

    else:
        form = EntryForm(instance = blog)

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

但是,如果我只使用render_to_response,那么它可以正常工作,但这不会改变顶部的URL。我想要的是在发布帖子后将用户重定向到新页面,我也想更改顶部的URL。

1 个答案:

答案 0 :(得分:7)

使用HttpResponseRedirect是可行的方法,但您需要将其与reverse结合使用:

from django.core.urlresolvers import reverse

### your other code
return HttpResponseRedirect(reverse('view_blog', args=(),
    kwargs={'author_id': blog.creator.id,'slug': blog.slug}))

希望能帮到你。