Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

django i18n_patterns hide default lang_code from url

I'm using the i18n_patterns to add a prefix of current lang_code to my url.

urlpatterns += i18n_patterns('',
    url(r'^', include('blaszczakphoto2.gallery.urls')),
)

It allowes me to get urls like /en/about-us/ , /pl/about-us/ etc.. My default language is pl

LANGUAGE_CODE = 'pl'

I want url like /about-us/ for clients viewing my site in polish lenguage. Is there any way to hide lang_code prefix from url for default lang_code?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Django >=1.10 can handle this natively. There is a new prefix_default_language argument in i18n_patterns function.

Setting prefix_default_language to False removes the prefix from the default language (LANGUAGE_CODE). This can be useful when adding translations to existing site so that the current URLs won’t change.

Source: https://docs.djangoproject.com/en/dev/topics/i18n/translation/#language-prefix-in-url-patterns

Example:

# Main urls.py:
urlpatterns = i18n_patterns(
    url(r'^', include('my_app.urls', namespace='my_app')), 
    prefix_default_language=False
)

# my_app.urls.py:
url(r'^contact-us/$', ...),

# settings:
LANGUAGE_CODE = 'en' # Default language without prefix

LANGUAGES = (
    ('en', _('English')),
    ('cs', _('Czech')),
)

The response of example.com/contact-us/ will be in English and example.com/cs/contact-us/ in Czech.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...