Elman Shokri
Elman Shokri

Reputation: 21

Set or change the DEFAULT_LANGUAGE in Django

I want the default language of my site to be Persian, not English! and DEFAULT_LANGUAGE is not working for me !

A part of my settings.py file :

LANGUAGES = (
    ('fa','Persian'),
    ('en','English'),
)

DEFAULT_LANGUAGE = 1

LANGUAGE_CODE = 'fa'

TIME_ZONE = 'Asia/Tehran'

USE_I18N = True

USE_L10N = True

USE_TZ = True

I also read these and they did not help:

Set or change the default language dynamically according to the user - Django

Django how to set the default language in the i18n_patterns?

Django: Can't change default language

Django: default language i18n

Please help me. thanks!

Upvotes: 2

Views: 5858

Answers (4)

Alasgar
Alasgar

Reputation: 142

In settings.py you probably have this middleware,and it takes default language as your browser's language.

'django.middleware.locale.LocaleMiddleware'

remove it and add custom middleware.

Upvotes: 3

Abdelslam Shehab
Abdelslam Shehab

Reputation: 1

  • Since this 'django.middleware.locale.LocaleMiddleware' middleware in settings takes default language as your browser's language as @Alasgar mention.
  • We can solve problem by creating new light middleware and put it before this middleware so we don't lose any of features that LocaleMiddleware gives us.
  1. Let us create new middleware file as following:
  • Create package folder inside your project folder name it 'middleware' and then create languages.py file. It would look something like this
- {YOUR_APP}/middleware/
  - __init__.py
  - languages.py
  1. Inside languages.py put the following code:
 

def SetDefaultLangMiddleware(get_response):

    def middleware(request):
        # Code to be executed for each request before processing it
        
        if not request.COOKIES.get('django_language'): # Language not selected by the user ?
            # Set your default language code here
            request.COOKIES['django_language'] = 'ar'

        response = get_response(request)
        # If you want to process anycode after the view is called
        
        return response

    return middleware

  1. In settings.py put your new middleware right before 'YOUR_APP_NAME.middleware.languages.SetDefaultLangMiddleware' 'django.middleware.locale.LocaleMiddleware'

Like this

Upvotes: 0

just change this: LANGUAGE_CODE = 'fa-ir'

python
django

List Of Language Code

Upvotes: 1

Vladimir
Vladimir

Reputation: 17

Here is fastest and simplest solution. In my case Django=="3.1" https://github.com/yifaneye/django-default-language

Upvotes: 0

Related Questions