Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect to a different view after processing a form getting NoReverseMatch error

I am making a blog app and I want to redirect to a different different url after I have processed the form, however the below given view is not working. I am unable to use neither HttpResponseRedirect nor simply redirect

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

However if I just use render_to_response then it works fine, but that does not change the url at the top. What I want is to redirect the user to a new page after publishing the post and I want to change the url at the top also.

like image 363
Sachin Avatar asked Dec 07 '11 20:12

Sachin


1 Answers

Using HttpResponseRedirect is the way to go, but you need to use that in conjunction with 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}))

Hope that helps you out.

like image 93
Brandon Avatar answered Nov 07 '22 06:11

Brandon