Reputation: 19
I've a problem about Django URL-redirection. The structure of the code is the following :
All functions are correctly called, the GET request is done but the page doesn't redirect in browser...
urls.py
urlpatterns = [
url(r'^reactors/$', views.reactors, name = 'reactors'),
url(r'^measurements/reactor/$', views.measurementReactor, name='measureReact'),
]
views.py
@login_required
def reactor(request):
if request.method == "POST" and request.is_ajax():
if request.POST.get('type') == "measurement" :
return redirect('/measurements/reactor/?ref='+request.POST.get('id'))
@login_required
def measurementReactor(request):
reactobj = reactor.objects.get(id=request.GET['ref'])
query = measurements.objects.filter(id_reactor=reactobj.id)
return render(request, "measureReact.html",{"query":query})
reactor.js
var table1 = $('#datatable').DataTable();
$('#datatable tbody').on('click', 'tr>th:not(.controls.mdl-data-table__cell--non-numeric)', function () {
var data = $(this).parent().find("[name=pk]").text();
$.ajax({
type : "POST",
data : {'csrfmiddlewaretoken' : csrftoken, 'id':data, 'type':"measurement"},
});
});
[EDIT] Thank you for your answers, i did this and it works !
#views.py
import json
@login_required
def reactors(request):
if request.POST.get('type') == "measurement" :
data = json.dumps({'url':'/measurements/reactor/?ref='+request.POST.get('id')})
return HttpResponse(data)
#reactor.js
$.ajax({
type : "POST",
data : {'csrfmiddlewaretoken' : csrftoken, 'id':data, 'type':"measurement"},
dataType: 'json',
success: function(data){
window.location.href = data["url"];
}
});
Upvotes: 1
Views: 1536
Reputation: 2094
As aman kumar suggested, your reactor view should return url
back to reactor.js and then use it to redirect to the desired page:
var table1 = $('#datatable').DataTable();
$('#datatable tbody').on('click', 'tr>th:not(.controls.mdl-data-table__cell--non-numeric)', function () {
var data = $(this).parent().find("[name=pk]").text();
$.ajax({
type : "POST",
data : {'csrfmiddlewaretoken' : csrftoken, 'id':data, 'type':"measurement"},
success: function(data){
window.location.href = data.url;
}
});
});
Upvotes: 0
Reputation: 3156
In ajax call you will get the data in json format, it will not change the url, better return the url on json fromt using HttpResponse and redirect that url from the javascript code.
@login_required
def reactor(request):
if request.method == "POST" and request.is_ajax():
import josn
if request.POST.get('type') == "measurement" :
data = josn.dump({'url':/measurements/reactor/?ref='+request.POST.get('id')})
return HttpResponse(data)
in the ajax call success method, catch the response and redirect using $window
Upvotes: 2