Login

Django 1.10 Internationalization Middleware

Author:
agusmakmun
Posted:
November 16, 2016
Language:
Python
Version:
1.10
Score:
0 (after 0 ratings)

Django 1.10 Internationalization Middleware, more complete tutorial: https://python.web.id/blog/how-to-implement-django-internationalization/

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import os
import pygeoip
from django.conf import settings
from django.utils import translation
from django.utils.deprecation import MiddlewareMixin

class LanguageMiddleware(MiddlewareMixin):
    """Django translation middleware
        * https://github.com/codingforentrepreneurs/Guides/blob/master/all/Django_Translation.md
    """

    def get_client_ip(self, request):
        """
        Get Client IP.
        Refference: http://stackoverflow.com/a/4581997/6396981
        """
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]
        else:
            ip = request.META.get('REMOTE_ADDR')
        return ip

    def process_request(self, request):
        geoipdb = os.path.join(settings.BASE_DIR, 'yourproject/geoipdb/GeoIP.dat')
        gi = pygeoip.GeoIP(geoipdb)

        client_ip = self.get_client_ip(request)
        client_country_code = gi.country_code_by_name(client_ip).lower()

        if 'lang' in request.GET:
            translation.activate(request.GET.get('lang'))
        elif client_country_code != 'id' and client_country_code != '':
            translation.activate('en')

"""
#1. settings.py
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    ......

    'django.middleware.locale.LocaleMiddleware',
    'yourproject.middleware.LanguageMiddleware',
]

from django.utils.translation import ugettext_lazy as _

LANGUAGE_CODE = 'en'
LANGUAGES = (
    ('en', _('English')),
    ('id', _('Indonesia'))
)
DEFAULT_LANGUAGE = 1
LOCALE_PATHS = (
    os.path.join(BASE_DIR, 'yourproject/locale'),
)


#2. urls.py
from django.conf import settings
from django.contrib import admin
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.views.i18n import JavaScriptCatalog
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^jsi18n/$', JavaScriptCatalog.as_view(), name='javascript-catalog'),
    url(r'^i18n/', include('django.conf.urls.i18n')),
    .....
    .....
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)



#3. Templates
{% load i18n %}
<form action="{% url 'set_language' %}" method="post">
  {% csrf_token %}
  <div class="form-group">
    <select name="language" onchange="javascript:form.submit()">
      <option value="en" {% if request.LANGUAGE_CODE == 'en' %}selected="selected"{% endif %}>English</option>
      <option value="id" {% if request.LANGUAGE_CODE == 'id' %}selected="selected"{% endif %}>Indonesia</option>
    </select>
  </div>
</form>
"""

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.