After migrating to Djanogo 4 from Django 2 I started having issues with the reverse path urls in templates. The following error was thrown:
django.urls.exceptions.NoReverseMatch: Reverse for 'activate' with arguments '('MQ', 'bwachb-fa5e0484e188dc10f2573f3eedf2dd11')' not found. 1 pattern(s) tried: ['en/activate/(?P<uidb64>[0-9A-Za-z_\\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$']
I created a test case to reproduce this issue:
def test_reverse_activation_url(self):
url = reverse('activate', args=['MQ', 'bwachb-fa5e0484e188dc10f2573f3eedf2dd11'])
self.assertEqual(url, "/en/activate/MQ/bwachb-fa5e0484e188dc10f2573f3eedf2dd11/")
Originally the urlpatterns was like this, and I managed to reproduce the same error running the testcase.
urlpatterns += i18n_patterns(
Django2: url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', core_views.activate, name='activate'),
Django4: re_path(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', core_views.activate, name='activate'),
)
- If I change the urlspatters as follows:
urlpatterns += i18n_patterns(
re_path(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})', core_views.activate, name='activate'),
)
The test case will fail because of no trail slash:
AssertionError: '/en/activate/MQ/bwachb-fa5e0484e188dc10f2573f3eedf2dd11' != '/en/activate/MQ/bwachb-fa5e0484e188dc10f2573f3eedf2dd11/'
- /en/activate/MQ/bwachb-fa5e0484e188dc10f2573f3eedf2dd11
+ /en/activate/MQ/bwachb-fa5e0484e188dc10f2573f3eedf2dd11/
? +
- If I change the urlspatters as follows, the test will pass.
urlpatterns += i18n_patterns(
path('activate/<uidb64>/<token>/', core_views.activate, name='activate'),
)
Why is there a difference in the link generated when using re_path and path? Mainly in this case the trail slash.
I also tried:
re_path(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/?$', core_views.activate, name='activate')
Which results NoReverseMatch And:
re_path(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/?', core_views.activate, name='activate')
Which results in the link with no trail slash error.
Can someone please shed some light into this? I already wasted so many hours...
I am currently on Django==4.2.5