I'm creating delete function using ajax. redirect doesn't work as expected.
js
function deleteEntry(entry) {
var id = $entry.data('id')
$.ajax({
url:'/blog/delete/' + id,
method: 'DELETE',
beforeSend: function(xhr) {
xhr.setRequestHeader('X-CSRFToken', csrf_token)
}
})
}
}
views.py
def delete_entry(request, pk):
if request.method == 'DELETE':
entry = get_object_or_404(Entry, id=pk)
entry.delete()
return HttpResponseRedirect(reverse_lazy('blog:list_entry'))
command line is like this when doing the function
[13/Sep/2018 16:06:02] "DELETE /blog/delete/14 HTTP/1.1" 302 0
[13/Sep/2018 16:06:02] "DELETE /blog/list HTTP/1.1" 200 9878
[13/Sep/2018 16:06:02] "GET / HTTP/1.1" 200 10605
I want to make the page redirect to blog/list
but the page redirects to /
. I don't want to create template for this view and also I'm thinking of doing something like confirm window so I want to call the function using js.
How can I fix this?
$.ajax({
url:'/blog/delete/' + id,
method: 'DELETE',
beforeSend: function(xhr) {
xhr.setRequestHeader('X-CSRFToken', csrf_token)
},
success: function () {
window.location.href = {% url 'the_get_url_you_wanted_to_redirect_to' %}
}
})
Do note this is a duplicate question asked quite a few times here in stackoverflow, so its best to search first before posting a new question. :) Best of luck!
One thing that seems to work well that isn't mentioned..
Ajax Call Success:
success: function (response) {
if("redirect" in response){
window.location.href = response["redirect"];
}
}
Instead of using HttpResponseRedirect you use this in your view
return JsonResponse({"redirect":'/customer/buyer'}, status=200)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.