I am using Django internationalization and use the get_current_language call to get the current language. However, that is a language code plus region code (e.g. en-gb), while I only want the language code (e.g. en).
How can I get just the two-letter language code?
You can simply split on the dash.
https://docs.djangoproject.com/en/1.11/topics/i18n/translation/#how-django-discovers-language-preference
If a base language is available but the sublanguage specified is not, Django uses the base language. For example, if a user specifies de-at (Austrian German) but Django only has de available, Django uses de.
This kind of expands on #mccainz's answer.
I propose you create a custom template filter, as documented here
#register.filter
def country_only(value):
return value[0:value.find("-")]
Usage would be:
{{lang|country_only}}
Related
I would like to use the same views for different supported languages.
For exemple I have the default language and the english.
In my main urls:
url(r'^posts/', include('posts.urls')), #for default language
url(r'^en/posts/', include('posts.urls')), #for english
The urls file of my posts app is like this:
url(r'^newpost/$', views.PostFormView.as_view(), name='add'),
url(r'^favorite/$', views.favorite, name='favorite'),
so, for example, both www.mysite.com/posts/add and www.mysite.com/en/posts/add send to the same view PostFormView and according to the url if it contains "/en/" or not I send the content in the right language.
However, the issue is with the redirect or revers sends always to the default language. For example 'posts:add' sends always to "www.mysite.com/posts/add" because I have url(r'^posts/', include('posts.urls')) before url(r'^en/posts/', include('posts.urls'))
are there any ways to use the same view for two different urls. Or, how can I handle multiple languages website? Do we have to duplicate all the apps for all the supported languages?
This is a long subject and it's not easy to cover everything but i'll try to cover as much as i can:
1 - Use django Internationalization and localization:
Django has a built-in function for multi language websites:
Internationalization and localization
2 - Use a single URL with different GET request:
You can add a GET request in your urls like : site.com/posts?lang=en. And try this in your views:
language = request.GET.get('lang')
and then pass the right template for this language.
example:
LANG_LIST = ['en', 'fa', 'fr']
if language.lower() in LANG_LIST:
template = '{}/posts/post.html'.format(language.lower())
else:
template = 'en/posts/post.html'
or you can use a single template with different language texts and just pass the language to the template and decide there.
Note: You should add users language to their session so you can retrieve the language even without a GET request.
Here is the docs for sessions:
How to use sessions | Django documentation | Django
Also you can add language to your users profile and retrieve the language from there. I recommend using both profile language and user sessions.
3 - Different urls (Your way):
I'm not a fan of this way of handling multi language websites really, but if you really need to do it this way then here you go:
You need different names for your urls lile posts_en, posts_fr and etc so you can redirect to the right page url.
You should get the page url in your view and check for language your using. You can do something like this: request.path.split('/').
Then you should check the language and decide which template to render just like option #2
There can be so many problems with this way of handling multiple languages so i don't think you should go with this one over the other two options.
I am setting
request.session['total_items'] = 3
in a views.py file of a django app
in template
i got to know that you can access it as {{request.session.total_items}}
Everything is fine and i'm able to get the value.
However,my question is that why it is not {{request.session['total_items']}} instead, since request.session is a dictionary like object.
For {{request.session['total_items']}}, its giving an error as following:
Could not parse the remainder: '['total_items']' from 'request.session['total_items']'
Any help would be appreciated ...
Do not confuse Django template language with Python Syntax. Django template language its a language on its own and have its own way of performing things. As doc suggests:
The goal is not to invent a programming language. The goal is to offer
just enough programming-esque functionality, such as branching and
looping, that is essential for making presentation-related decisions.
When you have enabled the django.core.context_processors.request it will enable the access to the values of a dictionary-like objects with the . notation.
This will convert any Python object into something that the Django template language will understand as it is its own language.
This also applies for the following:
Attribute lookups (eg. myobject.age)
Method calls (eg. myobject.age())
List indices (eg mylist.1)
The thing that is working it behind the scenes is the Context object.
You can read more on how it works here and here
And you can compare the Python controlstructure if to Django's template language.
if object:
myobject.dostuff()
to
{% if object %}
{{ myobject.dostuff }}
{% endif %}
If you want a closer match to Python you should check out
Jinja2
PyHAML
As you can see, django-pagination has polish (pl) translations - https://github.com/ericflo/django-pagination/tree/master/pagination/locale but I dont know, how to set polish language for django-pagination? (default english)
This should happen automatically.
Check your django settings if USE_I18N is set to True and if your LANGUAGE_CODE is set to pl.
For further information take a look at the django localization page. You can find a more detailed documentation of how the translation in django works here.
There's also a list of language codes, I guess pl should be correct.
You can either change the language setting of your browser, which will send the appropriate headers with each request and trigger the translation to be used, or you can provide a language setting selection so the user can choose their language.
You can roll your own code to provide this interface or use django-user-accounts.
You also might want to check that you have the appropriate middleware installed as described in this documenation.
Hy!
I would need to make urls based on language.
Example:
If I had the language english and subcategory named "articles" then the url might be like this:
/en/articles/...
If the language were portuguese and subcategory already translated is "artigos" then the url will be:
/pt/artigos/...
How can I do it?
I must use the urls.py or some monkeypatches?
thanks
This features is already existing in the yet-to-be released version 1.4. You can read about it in the release note.
If your really need this feature, and no existing app feets your needs, you can still try to apply the corresponding patch yourself.
Django LocaleURL is a piece of middleware that does exactly this. The documentation can be found in the source, or online.
Edit: I read over the fact that you want to translate the url itself... I'm not aware of any piece of code that provides this. Perhaps you could extend the LocalURL middleware to take care of the translations for you. Say you have a regex match like (?P<articles>\w+), you could in the middleware determine which view you want to use. Something like the following mapping perhaps?
if article_slug in ['articles', 'artigos', 'article']:
article(request) # Call the article view
I've been using transurlvania with great success, it does exactly what you need and more, however i see that in the next Django release django-i18nurls will be included in django core so perhaps it would be better to learn that
Can I use another language instead of english(say, french) for default django translation.
For example, instead for doing this:
messages.error(request, _('My message in english'))
I do this:
messages.error(request, _('Mon message en francais'))
Yeah, you could do that, and it would mostly work, but better would be to write them in English and then provide French translations (via the standard i18n approach), and to set the project's LANGUAGE_CODE to 'fr' as well.
That way, your code will be more easily reusable in other languages, and - perhaps more usefully to you if you're not worried about that - you'll be able to cleanly use French/other language translations already available in any third-party apps you want to add to your site, else you'll be mixing what Django thinks is default English (but is French) and thinks is French (and is French)
Allez! ;o)