如何在django上获取当前语言环境的“short_date_format”?

时间:2021-04-28 07:29:04

I have L10N successfuly set up on my project, and I'm able to translate dates to the correct format. But now I need the SHORT_DATE_FORMAT for the current locale on my templates, or in a context_processor.

我已经成功地在我的项目上设置了L10N,并且我能够将日期转换为正确的格式。但是现在我需要SHORT_DATE_FORMAT用于我的模板或context_processor中的当前语言环境。

Getting it from django.conf.settings always gives me the default value, m/d/Y. The locale was currently set to pt_BR, so the format should be d/m/Y.

从django.conf.settings获取它总是给我默认值m / d / Y.区域设置当前设置为pt_BR,因此格式应为d / m / Y.

In [42]: settings.LANGUAGE_CODE
Out[42]: 'pt-br'

In [43]: settings.USE_L10N
Out[43]: True

In [44]: settings.SHORT_DATE_FORMAT
Out[44]: 'm/d/Y'

Any clues?

By the way, what I'm really trying to do is: get the current locale's format so I can pass it to bootstrap-datepicker plugin. It's currently using m/d/Y and django is giving a date in the d/m/Y format.

顺便说一句,我真正想做的是:获取当前语言环境的格式,以便将其传递给bootstrap-datepicker插件。它目前正在使用m / d / Y而django正在以d / m / Y格式给出日期。

2 个解决方案

#1


2  

I had to do the following:

我必须做以下事情:

from django.conf import settings
from django.utils import formats 

correct_format = formats.get_format("SHORT_DATE_FORMAT", lang=settings.LANGUAGE_CODE)

#2


0  

I was able to do this using babel:

我能用babel做到这一点:

settings.py:

MIDDLEWARE_CLASSES = (
    ...
    'babeldjango.middleware.LocaleMiddleware',
    ...
)

context_processors.py:

def global_context(request):
    # Fixing the date format so bootstrap-datepicker understands.
    js_frm = request.locale.date_formats['medium'].pattern

    context = {
    ...

    return context

#1


2  

I had to do the following:

我必须做以下事情:

from django.conf import settings
from django.utils import formats 

correct_format = formats.get_format("SHORT_DATE_FORMAT", lang=settings.LANGUAGE_CODE)

#2


0  

I was able to do this using babel:

我能用babel做到这一点:

settings.py:

MIDDLEWARE_CLASSES = (
    ...
    'babeldjango.middleware.LocaleMiddleware',
    ...
)

context_processors.py:

def global_context(request):
    # Fixing the date format so bootstrap-datepicker understands.
    js_frm = request.locale.date_formats['medium'].pattern

    context = {
    ...

    return context