I am using a redirect in Django from django.shortcuts import redirect
What I want, is for the user to be displayed a Javascript alert message before being redirected.
Here is what I've got so far:
response = redirect("someUrl")
response.write('<script>alert(\'You must remove an item before adding another\');</script>')
response['location'] += "?active=" + "all"
return response
The redirect works, but the Javascript does not. I also tried
response = HttpResponse('<script>alert(\'You must remove an item before adding another\');</script>')
return response
This triggers the alert window, but I'm not sure how to add an equivalent redirect as the method above.
You can use js appproach window.location
url = 'someUrl'
resp_body = '<script>alert("You must remove an item before adding another");\
window.location="%s"</script>' % url
return HttpResponse(resp_body)
You are getting confused between frontend and backend. When this view is requested by the user, the server (via Django's HTTPResponseRedirect) is sending a 302 redirect HTTP response that tells the browser to redirect to a different page. This is different to a normal 200 response (i.e. a normal Django response object, not a redirect) within which you could include a javascript alert.
You need to show that javascript on the view you are initially loading before the user is returned the redirect response.
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