how to automatically redirect the user to a specific language in django

Viewed 281

I have added new languages to my website and now it is available in English, French and Arabic Everything works fine, I couldn't figure out how to change the default language Currently when the user does not select any language, the site is displayed in English. Some users are complaining that English is not widely used in my country and the site should be in Arabic instead, so I want to do this: if the user does not select any language it will be redirected automatically to arabic.

So when i visit my website like this: http://127.0.0.1:8000/ i will be automatically redirected to: http://127.0.0.1:8000/ar/

Is it possible to do something like this or do I have to change the default code for the whole website.

i have this code in urls.py

    urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include('core.urls')),
    path('user/',include('users.urls')),
    path('dashboard/',include('dashboard.urls')),
    path('wallet/',include('wallet.urls')),
    path('administration/',include('administration.urls')),
    path('chaining/', include('smart_selects.urls')),
    path('__debug__/', include(debug_toolbar.urls)),

]

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

urlpatterns += i18n_patterns (
    path('',include('core.urls')),
    path('user/',include('users.urls')),
    path('dashboard/',include('dashboard.urls')),
    path('wallet/',include('wallet.urls')),
    path('administration/',include('administration.urls')),

)

and this is my settings

from django.utils.translation import gettext_lazy as _
LOCALE_PATHS = ( os.path.join(BASE_DIR, 'locale'), )
LANGUAGE_CODE = 'en'
LANGUAGES =(
('en', ('english')),
('ar', ('Arabic')),
('fr', ('french'))
)
1 Answers

If you change the default language code, you would have to re-write all the strings in your code, since the base language doesn't go into po/mo files.

Here are a few options.

  1. Don't change anything. Django's locale middleware is quite good at discovering language preferences and redirects users to their language anyway. It first checks url, then any cookies, then browser preferences. Only then, if nothing is found, Django reverts to the default language (How Django discovers language preferences).

  2. Write your custom middleware. You could start with the built-in locale middleware and adjust it so that at the end it doesn't revert to default language but to your target language.

  3. Handle it in your server settings. You could instruct your server to redirect all requests send to your domain without language code to your domain with your target language code. But I wouldn't recommend this approach, since you'd loose the nice features of Django's language detection, as described in 1.

Related