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_patterns

urlpatterns = i18n_patterns(
path('admin/', admin.site.urls),
path('cart/', include('cart.urls', namespace='cart')),
path('orders/', include('orders.urls', namespace='orders')),
path('payment/', include('payment.urls', namespace='payment')),
path('coupons/', include('coupons.urls', namespace='coupons')),
path('rosetta/', include('rosetta.urls')),
path('', include('shop.urls', namespace='shop')),
)

You can combine non-translatable standard URL patterns and patterns under i18n_patterns so that some patterns include a language prefix and others don't. However, it's best to use translated URLs only to avoid the possibility that a carelessly translated URL matches a non-translated URL pattern.

Run the development server and open http://127.0.0.1:8000/ in your browser. Django will perform the steps described previously in the How Django determines the current language section to determine the current language, and it will redirect you to the requested URL, including the language prefix. Take a look at the URL in your browser; it should now look like http://127.0.0.1:8000/en/. The current language is the one set by the Accept-Language header of your browser if it is Spanish or English, otherwise the default LANGUAGE_CODE (English) defined in your settings.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset