Adding javascript to a Django redirect (HttpResponse)
<p>I am using a redirect in Django <code>from django.shortcuts import redirect</code></p>

<p>What I want, is for the user to be displayed a Javascript alert message before being redirected.</p>

<p>Here is what I've got so far:</p>

<pre><code>response = redirect("someUrl")
response.write('&lt;script&gt;alert(\'You must remove an item before adding another\');&lt;/script&gt;')
response['location'] += "?active=" + "all"
return response
</code></pre>

<p>The redirect works, but the Javascript does not. I also tried</p>

<pre><code>response = HttpResponse('&lt;script&gt;alert(\'You must remove an item before adding another\');&lt;/script&gt;')
return response
</code></pre>

<p>This triggers the alert window, but I'm not sure how to add an equivalent redirect as the method above.</p>

<p>You are getting confused between frontend and backend. When this view is requested by the user, the server (via Django's <a href="https://docs.djangoproject.com/en/1.10/_modules/django/http/response/#HttpResponseRedirect" rel="nofollow"><code>HTTPResponseRedirect</code></a>) is sending a <a href="https://en.wikipedia.org/wiki/HTTP_302" rel="nofollow"><code>302</code> redirect HTTP response</a> that tells the browser to redirect to a different page. This is different to a normal <code>200</code> response (i.e. a normal Django response object, not a redirect) within which you could include a javascript alert. </p>

<p>You need to show that javascript on the view you are initially loading <em>before</em> the user is returned the redirect response. </p>

python django redirect httpresponse