After solving this problem here, there's another one: if you use the translation url system here https://docs.djangoproject.com/en/1.8/topics/i18n/translation/ you will see you add patterns like urlpatterns += i18n_patterns(...)
.
The problem is that the base url without the language is not taken in account ie:
resolve('/fr/produits/')
works,- but
resolve('/produits/')
doesnt work and raises 404.
How to solve this?
Here are my urls:
urlpatterns = [
url(r'^debug/?$', p_views.debug, name='debug'),
url(r'^i18n/', include('django.conf.urls.i18n')),
url(r'^login/(\w*)', p_views.login, name='login'),
url(r'^admin/', include(admin_site.urls)),
url(r'^public/(?P<path>.*)$',
'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT},
name='url_public'
),
]
urlpatterns += i18n_patterns(
url(_(r'^produits/detail/(?P<slug>[a-zA-Z0-9-_]+)/$'),
p_views.ProduitDetailView.as_view(), name='produits_detail'),
url(_(r'^produits/'),
p_views.IndexView.as_view(), name='produits_index'),
)
And here's the very simple URL-tester I've made (which corresponds to the /debug
view):
def debug(req):
def test(url):
try:
return u'<pre>{0} {1}</pre>'.format(url, resolve(url))
except Resolver404:
return u'<pre>{0} {1}</pre>'.format(url, 'None')
response = HttpResponse()
response.write(test('produits'))
response.write(test('produits/'))
response.write(test('/produits'))
response.write(test('/produits/'))
response.write(test('/fr/produits'))
response.write(test('/fr/produits/'))
response.write(test('/en/products/'))
response.write(test('/sv/produkter/'))
return response
Here's the http://localhost:8000/debug
page:
produits None
produits/ None
/produits None
/produits/ None
/fr/produits None
/fr/produits/ ResolverMatch(func=produits.views.IndexView, args=(), kwargs={}, url_name=produits_index, app_name=None, namespaces=[])
/en/products/ None
/sv/produkter/ None
The three lastest lines should all return ResolverMatch(...)
because they are all valid URLs.