This note for me, that always use Reverse URL while accesing URL, make action or build URL. Using reverse will reduce your risk while developing Django applications. In this example, I will show how to use reverse url in Unit Testing with Client browser.
This is example URL :
urls.py
1 2 3 4 | url(r’^index/$’, ‘schools_index’, name=’home’), url(r’^check/(?P<schools>d{4})/(?P<abbrev>[a-zA-Z]{3})/$’, ‘schools_name’, name=’schools’), url(r’^check/(?P<schools>d{4})/$’, ‘schools_name’, name=’schools’), url(r’^check/$’, ‘schools_name’, name=’schools’), |
Now, in some unit test,
1 2 3 4 5 6 7 8 9 10 11 12 | from django.test.client import Client from django.test import TestCase class SchoolTestCase(TestCase): def setUp(self): self.browser = Client() def test_index_page(self): resp = self.browser.get(reverse(‘my-app-name-space:home’)) def test_check(self): resp = self.browser.get(reverse(‘my-app-name-space:schools’, kwargs={‘schools’: ‘2005’, ‘abbrev’: ‘AB’})) |
You can doing argument in reverse,
1 | reverse(‘schools’, args=[‘2005’]) |
Or passing keyword arguments in reverse :
1 | reverse(‘schools’, kwargs={‘schools’: ‘2005’, ‘abbrev’: ‘AB’}) |
Always use reverse! 🙂