Adding a language prefix to URL patterns

Django allows you to add a language prefix to your URL patterns. For example, the English version of your site can be served under a path starting /en/, and the Spanish version /es/.

To use languages in URL patterns, you have to use the LocaleMiddleware provided by Django. The framework will use it to identify the current language from the requested URL. You added it previously to the MIDDLEWARE setting of your project, so you don't need to do it now.

Let's add a language prefix to our URL patterns. Edit the main urls.py file of the myshop project and add i18n_patterns() as follows:

from django.conf.urls.i18n import i18n_patternsurlpatterns = i18n_patterns( path('admin/', admin.site.urls), path('cart/', ...

Get Django 2 by Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.