How to find the location URL in a Django response object?

Joseph Turian picture Joseph Turian · Oct 31, 2011 · Viewed 8.4k times · Source

Let's say I have a Django response object.

I want to find the URL (location). However, the response header does not actually contain a Location or Content-Location field.

How do I determine, from this response object, the URL it is showing?

Answer

pyrospade picture pyrospade · Feb 27, 2014

This is old, but I ran into a similar issue when doing unit tests. Here is how I solved the problem.

You can use the response.redirect_chain and/or the response.request['PATH_INFO'] to grab redirect urls.

Check out the documentation as well! Django Testing Tools: assertRedirects

from django.core.urlresolvers import reverse
from django.test import TestCase


class MyTest(TestCase)
    def test_foo(self):
        foo_path = reverse('foo')
        bar_path = reverse('bar')
        data = {'bar': 'baz'}
        response = self.client.post(foo_path, data, follow=True)
        # Get last redirect
        self.assertGreater(len(response.redirect_chain), 0)
        # last_url will be something like 'http://testserver/.../'
        last_url, status_code = response.redirect_chain[-1]
        self.assertIn(bar_path, last_url)
        self.assertEqual(status_code, 302)
        # Get the exact final path from the response,
        # excluding server and get params.
        last_path = response.request['PATH_INFO']
        self.assertEqual(bar_path, last_path)
        # Note that you can also assert for redirects directly.
        self.assertRedirects(response, bar_path)