Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 723
Joseph Turian Avatar asked Oct 31 '11 01:10

Joseph Turian


2 Answers

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)
like image 197
pyrospade Avatar answered Sep 20 '22 18:09

pyrospade


The response does not decide the url, the request does.

The response gives you the content of the response, not the url of it.

like image 29
Wolph Avatar answered Sep 20 '22 18:09

Wolph