136👍
Django 1.4:
https://docs.djangoproject.com/en/1.4/topics/testing/#django.test.TestCase.assertRedirects
Django 2.0:
SimpleTestCase.assertRedirects(response, expected_url, status_code=302, target_status_code=200, msg_prefix='', fetch_redirect_response=True)
Asserts that the response returned a status_code redirect status, redirected to expected_url (including any GET data), and that the final page was received with target_status_code.
If your request used the follow argument, the expected_url and target_status_code will be the url and status code for the final point of the redirect chain.
If fetch_redirect_response is False, the final page won’t be loaded. Since the test client can’t fetch external URLs, this is particularly useful if expected_url isn’t part of your Django app.
Scheme is handled correctly when making comparisons between two URLs. If there isn’t any scheme specified in the location where we are redirected to, the original request’s scheme is used. If present, the scheme in expected_url is the one used to make the comparisons to.
60👍
You could also follow the redirect with:
response = self.client.get('/myprofile/data/some_id/', follow=True)
which would mirror the user experience in the browser and make assertions of what you expect to find there, such as:
self.assertContains(response, "You must be logged in", status_code=401)
- [Django]-Django order_by query set, ascending and descending
- [Django]-Altering one query parameter in a url (Django)
- [Django]-Django upgrading to 1.9 error "AppRegistryNotReady: Apps aren't loaded yet."
38👍
You can check response['Location']
and see if it matchs with the expected url. Check also that status code is 302.
- [Django]-Setting the selected value on a Django forms.ChoiceField
- [Django]-Sending images using Http Post
- [Django]-Equivalent of PHP "echo something; exit();" with Python/Django?
16👍
response['Location']
doesn’t exist in 1.9. Use this instead:
response = self.client.get('/myprofile/data/some_id/', follow=True)
last_url, status_code = response.redirect_chain[-1]
print(last_url)
- [Django]-Django filter on the basis of text length
- [Django]-Django py.test does not find settings module
- [Django]-PicklingError: Can't pickle <class 'decimal.Decimal'>: it's not the same object as decimal.Decimal
2👍
You can use assertRedirects eg:
response = self.client.get('/sekrit/')
self.assertRedirects(response, '/other/login/?next=/sekrit/')
If you need to get url which redirected
If follow
is True
You will get url in
response.redirect_chain[-1]
If follow
is False
response.url
- [Django]-Django – accessing the RequestContext from within a custom filter
- [Django]-Setting DEBUG = False causes 500 Error
- [Django]-How to upload a file in Django?