How to fork LocaleMiddleware? I need to make a small change.

14 views
Skip to first unread message

Oleg Barbos

unread,
May 6, 2020, 8:41:39 AM5/6/20
to Django users
When LocaleMiddleware sees the request coming in, it tries to parse the language from the request. See https://github.com/django/django/blob/92507bf3ea4dc467f68edf81a686548fac7ff0e9/django/utils/translation/trans_real.py#L46 for the regular expression used. The allowed format is: any sequence of word characters, and optionally a dash and more word characters, after that it expects either the end of the string, or a /. In my case, it matches id-button/, and understands that id-button is the language prefix for that request, causing Django to activate the id language.

I need to change this behaviour, so it would check if second part like "button" is in a whitelist of languages from SETTINGS.
so the languages "id", "de", "zh-Hans" should work properly, but when slug is "id-button/" - it should get English language.

Aldian Fazrihady

unread,
May 6, 2020, 9:39:00 AM5/6/20
to django...@googlegroups.com
You can just extend LocaleMiddleware like this:
```
class MyLocaleMiddleware(LocaleMiddleware):

    def process_request(self, request):
        super().process_request(request)
        # TODO: add my custom code
```
Save it to a python file, such as `middleware.py`

On the django settings file, replace the LocaleMiddleware with yours:
```
MIDDLEWARE = [
    '<my app folder>.<my middleware python file base name>.MyLocaleMiddleware',
]
```

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/75b39a9f-05b6-430c-bf78-3b6e6cc0a641%40googlegroups.com.


--
Regards,

Reply all
Reply to author
Forward
0 new messages