Reputation: 565
I'm trying to redirect to another view in a django app. Right now, I have an ajax call to the update_view view and from there I try to redirect to another view called gameover with a game_id.
Currently, I'm trying this:
def update_view(request):
return HttpResponseRedirect(reverse('gameover', args=(game_id,)))
However, when I do this, it won't load the page and every other technique I've tried always has "update_view" in the URL, which isn't correct as the url mapping has gameover coming off the root.
Thank you for all the help!
Upvotes: 0
Views: 1033
Reputation: 34553
Because you're calling the view via Ajax, you would need to do the redirect on the client-side, by passing back the URL to redirect to, or knowing it ahead of time. With that URL, you can change the location in JavaScript. I would simply return the url you want to redirect to as JSON. This example assumes you're using jQuery to make the Ajax call:
import json
def update_view(request):
# more code
redirect_url = reverse('gameover', args=(game_id,), kwargs={})
return HttpResponse(json.dumps({'redirect_url': redirect_url},
ensure_ascii=False), mimetype='application/json')
(function($) {
$(function() {
$.ajax({
type: 'post',
url: 'path/to/your/view/',
dataType: 'json',
success: function(data, textStatus, jqXHR) {
window.top.location = data.redirect_url;
}
});
});
})(jQuery)
You can learn more about jQuery's Ajax implementation here: http://api.jquery.com/jQuery.ajax/. There is a shothand method for doing a post, $.post()
, I just chose to use the standard $.ajax()
for demonstrative purposes.
Upvotes: 1