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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With