I use i18n_patterns
What should I do so that http://localhost:8000 didn't redirect to url prefixed with language code?
In addition, I want to supply language, taken from session, not request.LANGUAGE_CODE
I found following code:
class NoPrefixLocaleRegexURLResolver(LocaleRegexURLResolver):
#property
def regex(self):
language_code = get_language()
if language_code not in self._regex_dict:
regex_compiled = (re.compile('' % language_code, re.UNICODE)
if language_code == settings.LANGUAGE_CODE
else re.compile('^%s/' % language_code, re.UNICODE))
self._regex_dict[language_code] = regex_compiled
return self._regex_dict[language_code]
However, there is problem with that code in checking if language_code == settings.LANGUAGE_CODE. If I enter http://localchost:8000, it will not redirect, but supply a page with translation from settings.LANGUAGE_CODE instead of request.session.get('django_language'). As I understood, I can't access request, so what should be done?
Related
I have a web set up with 3 languages (['es', 'en', 'it']) in Angular that works with the Django server.
Django by default has the English local path defined as /en, I want the url of the English configuration to be '/us' (by default it is '/ en'), I just want to change it for English, for 'es' or 'it' as it comes by default is fine.
I want the URL to look like this myurl.com/us in English, how would you recommend me to make this change?
The structure is the following:
-apps
--webapp
---templates
----webapp
-----en (inside index.html)
-----es (inside index.html)
-----it (inside index.html)
-conf
--settings.py
-middleware
--locale.py
conf.settings.py have this language configuration
LANGUAGES = (
('es', _('Spanish')),
('it', _('Italian')),
('en', _('English')),
)
LANGUAGE_CODE = 'es'
LANGUAGE_CODES = [language[0] for language in LANGUAGES]
Additionally I have configured a middleware to recognize the user's location and place the corresponding language code in the URL
from django.conf import settings
from .utils.geolocation import get_language_by_ip
cookie_name = settings.LANGUAGE_COOKIE_NAME
class LocalizationMiddleware(object):
def get_language_cookie(self, request):
return request.COOKIES.get(cookie_name)
def set_language_cookie(self, request, value):
request.COOKIES[cookie_name] = value
def get_i18n_url_language(self, request):
url = request.path.split('/')
if len(url) > 1 and len(url[1].split('-')[0]) == 2:
return url[1]
return None
def process_request(self, request):
language = self.get_i18n_url_language(request)
if language is not None and language not in settings.LANGUAGE_CODES:
return
if language is None:
language = self.get_language_cookie(request)
if language is None:
language = get_language_by_ip(request)
if language is None:
language = settings.LANGUAGE_CODE
self.set_language_cookie(request, language)
return None
def process_response(self, request, response):
response.set_cookie(cookie_name, request.COOKIES.get(cookie_name, settings.LANGUAGE_CODE))
return response
This all works fine, however I want the url for the English language to change from .../en to .../us
I am currently upgrading Django from 1.11 to 2.0 (to 2.2 in the long run). But recently I bumped into a problem which a can't solve for quiet some time. LocaleRegexURLResolver has been removed in 2.0 without any warning and the whole code has been refactored. Sadly we were using LocaleRegexURLResolver and I am not sure how to replicate it's functionality in the current version of Django. Any ideas?
class SiteLocaleRegexURLResolver(LocaleRegexURLResolver):
"""
Overrides LocaleRegexURLResolver to use specified default language
by site instead of global default language
"""
def __init__(
self, urlconf_name, site, default_kwargs=None, app_name=None, namespace=None,
prefix_default_language=True
):
super(LocaleRegexURLResolver, self).__init__(
None, urlconf_name, default_kwargs, app_name, namespace,
)
self.prefix_default_language = prefix_default_language
self.default_language = site.language_code
#property
def regex(self):
language_code = get_language() or self.default_language
if language_code not in self._regex_dict:
if language_code == self.default_language and not self.prefix_default_language:
regex_string = ''
else:
regex_string = '^%s/' % language_code
self._regex_dict[language_code] = re.compile(regex_string, re.UNICODE)
return self._regex_dict[language_code]
Basically it changes the default language. In UK, site /docs/ would be in english and /fr/docs/ in french. In FR on the other hand, /docs/ would be in french and /uk/docs/ in english
I'm trying to build some middleware in my Django project that redirects the user to a 'https' link if their request isn't initially to https. The code below is not redirecting the user under any of the tests that I've run (i.e. user enters 'www.example.com', 'http://example.com,', http://www.example.com', etc.
Can any of you spot the problem with this code? Normally, I'd use print statements to see what the path is being set to, but I can't do that on my live server (or at least I don't know how to):
from django.http import HttpResponseRedirect
from django.utils.deprecation import MiddlewareMixin
class RedirectMiddleware(MiddlewareMixin):
def process_request(self, request):
host = request.get_host()
if host == 'www.example.com' or 'example.com':
path = request.build_absolute_uri()
domain_parts = path.split('.')
if domain_parts[0] == 'http://www':
path = path.replace("http://www","https://www")
return HttpResponseRedirect(path)
elif domain_parts[0] == 'www':
path = path.replace("www","https://www")
return HttpResponseRedirect(path)
elif domain_parts[0] == 'http://example':
path = path.replace("http","https")
return HttpResponseRedirect(path)
elif domain_parts[0] == 'example':
path = path.replace("example","https://www.example")
return HttpResponseRedirect(path)
else:
pass
else:
pass
Thanks again guys
You can add the following to your settings file
SECURE_SSL_REDIRECT = True
See https://docs.djangoproject.com/en/2.1/ref/middleware/#ssl-redirect
You'll also need to add the following to your middlewares
'django.middleware.security.SecurityMiddleware',
It's a settings available from Django 1.8+
Am Working on Arabic-English Translation using 'Model Translation'.Once i login and change to arabic and then logout language changes to english.
This is my logout code:,I have activated language after logout and it prints language as 'ar' but it displays english.Please help me
def profile_logout(request,mode=None, **kwars):
lang = request.LANGUAGE_CODE
response = logout(request, **kwars)
translation.activate(lang)
print "langggggggggggggggggggggggggggggggggg",request.LANGUAGE_CODE
return response
I made some changes to my views by creating sessions.Hope someone will find use with this.This Worked for me.
def profile_logout(request,mode=None, **kwars):
lang = request.LANGUAGE_CODE
translation.activate(lang)
language=request.session.get('django_language')
print "languageeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",language
response = logout(request, **kwars)
if language is not None:
request.session['django_language'] = language
print
"request.session['django_language']request.session['django_language']request.session['django_language']",request.session['django_language']
return response
Or Refer:
``https://github.com/ludwiktrammer/django/commit/adfb2c114f94df4a77a9424001e300f0552c6e20
You should activate the translation before processing the template, e.g. before calling logout. something like:
def profile_logout(request,mode=None, **kwars):
lang = request.LANGUAGE_CODE
translation.activate(lang)
response = logout(request, **kwars)
print "langggggggggggggggggggggggggggggggggg",request.LANGUAGE_CODE
return response
I want my app will be available in multiple languages (let say two,one is default english and one more).
And these both options available in my home page and there must be a link shown which makes user able to select his choice of language.
I am reading the Django official documentation for this
so any one can let me know the general idea how I can do that.
and one more thing......in settings.py there is default LANGUAGE_CODE = 'en-us' given,BUT as I want my app in more then one language so How i can specify that country code here.
like this works LANGUAGE_CODE = 'en-us','es-MX (Spanish)' or I have to do it in some way.
And what is the purpose of this .po extension in this.
settings.py
LANGUAGE_CODE='en_us'
gettext = lambda s: s
LANGUAGES = (
('en', gettext('English')),
('de', gettext('German')),
)
MIDDLEWARE_CLASSES = (
...
'lang.SessionBasedLocaleMiddleware',
)
lang.py
from django.conf import settings
from django.utils.cache import patch_vary_headers
from django.utils import translation
class SessionBasedLocaleMiddleware(object):
"""
This Middleware saves the desired content language in the user session.
The SessionMiddleware has to be activated.
"""
def process_request(self, request):
if request.method == 'GET' and 'lang' in request.GET:
language = request.GET['lang']
request.session['language'] = language
elif 'language' in request.session:
language = request.session['language']
else:
language = translation.get_language_from_request(request)
for lang in settings.LANGUAGES:
if lang[0] == language:
translation.activate(language)
request.LANGUAGE_CODE = translation.get_language()
def process_response(self, request, response):
patch_vary_headers(response, ('Accept-Language',))
if 'Content-Language' not in response:
response['Content-Language'] = translation.get_language()
translation.deactivate()
return response
Access different languages http://example.com/?lang=de
And finaly let django create your .po files. Heres the documentation for that.
You want internationalization (or localization) of your software. With C it is often done thru gettext (which is related to .po files). Probably django uses these things.