the question: How do i redirect to a page in django but "fake" it as an ajax request?
So i have a post data request – done via ajax (jQuery). This gets sent to my django server, which adds the data (or removes it!) and then responds with a "well done you added some data" page.
This success page begins with:
{% extends request.is_ajax|yesno:"base_ajax.htm,base.htm" %}
which is a nice way of adding in all sorts of headers if the request wasn’t an ajax one, and ignoring the headers if it was. I added this so the site works both with and without javascript (do we need to do that anymore?)
And then i added a post-redirect-get (that is, the post part of the view doesn’t return render_to_response but rather return redirect('url here')
And now the problem is that the redirect forgets that the initial request was an ajax one. So i always end up loading the entire page – headers and all – into a div, which isn’t what i want.
So, i’d like to be able to tell the redirect that it should pretend to be an ajax request
How do i do that?
UPDATE: to anybody reading this in "the future (with jetpacks!)" redirects don’t carry the header information over – see https://www.rfc-editor.org/rfc/rfc2616#section-7.1
in the end, i went and did this:
return redirect(self.success_redirect + '/' + str(int(request.is_ajax())))
and then, for the view that i redirected to i had:
url(r'^editStorySuccess/(?P<ajax>\d+)$',
showAfterCheckingAjax,
{
'template':'stories/editStorySuccess.html'
},
'editStorySuccess'
),
and in the showAfterCheckingAjax view i just had:
if int(ajax):
request.META['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest'
return render_to_response(template, {'user':request.user},
context_instance=RequestContext(request))
and that works for me!
Create a different URL that presents the same view as the URL you’re redirecting to now but with an additional GET parameter. You can use this GET parameter to modify the template that is being used to serve the view. Either way, a redirect is considered a new request so you have to do something to pass this additional information to this request.