Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding javascript to a Django redirect (HttpResponse)

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.

like image 854
hammerabi Avatar asked Jul 27 '26 16:07

hammerabi


2 Answers

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)
like image 154
deedee Avatar answered Jul 30 '26 05:07

deedee


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.

like image 45
Timmy O'Mahony Avatar answered Jul 30 '26 06:07

Timmy O'Mahony



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!