简体   繁体   English

如何翻译 Django 日历中星期和月份的名称

[英]How to translate the name of days of the week and months in Django calendar

I would like to ask how can I change the name of the days of the week and month from the original English to eg Polish in the calendar rendered in Django我想问如何在 Django 呈现的日历中将星期和月份的名称从原始英文更改为例如波兰语

I tried to find a solution in changing the language in the settings but nothing works I also tried to use LocalHTMLCalendar but it didn't work我试图找到一个解决方案来更改设置中的语言,但没有任何效果我也尝试使用 LocalHTMLCalendar 但它没有用

this is my utlis.py file这是我的 utlis.py 文件

class Calendar(LocaleHTMLCalendar):
    def __init__(self, year=None, month=None):
        self.year = year
        translation.activate('pl')
        self.month = month
        super(Calendar, self).__init__()

    # formats a day as a td
    # filter events by day
    def formatday(self, day, events):
        events_per_day = events.filter(start_time__day=day)
        d = ''
        for event in events_per_day:
            d += f'<li> {event.get_html_url} </li>'

        if day != 0:
            return f"<td><span class='date'>{day}</span><ul> {d} </ul></td>"
        return '<td></td>'

    # formats a week as a tr
    def formatweek(self, theweek, events):
        week = ''
        for d, weekday in theweek:
            week += self.formatday(d, events)
            print()
        return f'<tr> {week} </tr>'

    # formats a month as a table
    # filter events by year and month
    def formatmonth(self, withyear=True):
        events = Event.objects.filter(start_time__year=self.year, start_time__month=self.month)

        cal = f'<table border="0" cellpadding="0" cellspacing="0" class="calendar">\n'
        cal += f'{self.formatmonthname(self.year, self.month, withyear=withyear)}\n'
        cal += f'{self.formatweekheader()}\n'
        for week in self.monthdays2calendar(self.year, self.month):
            cal += f'{self.formatweek(week, events)}\n'
        return cal

and this is my views.py file这是我的views.py文件

def get_date(req_day):
    translation.activate('pl')

    if req_day:
        year, month = (int(x) for x in req_day.split('-'))
        return date(year, month, day=1)
    return datetime.today()


def prev_month(d):
    first = d.replace(day=1)
    prev_month = first - timedelta(days=1)
    month = 'month=' + str(prev_month.year) + '-' + str(prev_month.month)
    return month


def next_month(d):
    days_in_month = calendar.monthrange(d.year, d.month)[1]
    last = d.replace(day=days_in_month)
    next_month = last + timedelta(days=1)
    month = 'month=' + str(next_month.year) + '-' + str(next_month.month)
    return month


class CalendarView(LoginRequiredMixin, generic.ListView):
    login_url = 'signup'
    model = Event
    template_name = 'sytoapp/calendar.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        d = get_date(self.request.GET.get('month', None))
        cal = Calendar(d.year, d.month)
        print(d.month)
        html_cal = cal.formatmonth(withyear=True)
        context['calendar'] = mark_safe(html_cal)
        context['prev_month'] = prev_month(d)
        context['next_month'] = next_month(d)
        return context

I would appreciate any hints我会很感激任何提示

Perhaps you can take the working example below and adapt the principle to your actual case.也许您可以采用下面的工作示例并将该原理应用于您的实际情况。 Notice the _ in front of every string required for translation.注意翻译所需的每个字符串前面的 _。

However, even with my example, this involves some further work:但是,即使以我的示例为例,这也涉及一些进一步的工作:

  • when happy with your.py code, you have to generate the.po file for it (ie gettext editable translation file for the target language);如果对您的.py 代码感到满意,您必须为其生成.po 文件(即目标语言的gettext可编辑翻译文件); this can be generated with gettext -o yourfile.po yourfile.py by using gettext from gettext tools (note: on my local system, the name I gave for this example file is 'test_i18n.py'; this name (but without the extension) is also specified explicitly in the language = gettext.translation('test_l10n', locale_path, [current_locale] line in my code below; the name specified in this line must match the name of the actual这可以通过使用 gettext 工具中的 gettext 使用gettext -o yourfile.po yourfile.py生成(注意:在我的本地系统上,我为这个示例文件提供的名称是“test_i18n.py”;这个名称(但没有扩展名) ) 在下面我的代码中的language = gettext.translation('test_l10n', locale_path, [current_locale]行中也明确指定;此行中指定的名称必须与实际的名称匹配.py program file .py 程序文件.mo compiled language file generated further in this localization process (the fourth bullet down here); .mo 在本地化过程中进一步生成的编译语言文件(此处的第四个项目符号);
  • a "Language: xx\n" line must be inserted into the header block of the.po file (say, after the "Language-Team: etc." line), where xx is the target language ID (which in your case is pl);必须将"Language: xx\n"行插入到 .po 文件的 header 块中(例如,在"Language-Team: etc."行之后),其中 xx 是目标语言 ID(在您的情况下是pl);
  • translate the.po entries using, for example, Poedit or Gtranslator ;使用例如PoeditGtranslator翻译 the.po 条目;
  • when happy with your translation, you have to generate the.mo file (ie compiled translation file) from the.po file;当您对您的翻译感到满意时,您必须从.po 文件生成.mo 文件(即编译后的翻译文件); Poedit will do this automatically, but this can be generated also with msgfmt yourfile.po -o yourfile.mo by using msgfmt from gettext tools; Poedit 会自动执行此操作,但也可以使用 gettext 工具中的 msgfmt 生成msgfmt yourfile.po -o yourfile.mo
  • put (copy or move) the generated.mo file to a locale path relative to your code;将生成的.mo 文件放置(复制或移动)到相对于您的代码的语言环境路径; for example, on same location as the.py program, a /locale/xx/LC_MESSAGES/ path must exist (or be generated) with the.mo file inside it (notes: the 'xx' is the target language ID and the.mo filename must match the name例如,在与 .py 程序相同的位置, /locale/xx/LC_MESSAGES/路径必须存在(或生成),其中包含 .mo 文件(注意:'xx' 是目标语言 ID,. mo 文件名必须与名称匹配of the main.py program file main.py 程序文件的specified explicitly in the language = gettext.translation('test_l10n', locale_path, [current_locale] line);language = gettext.translation('test_l10n', locale_path, [current_locale] line);
  • run the program, it should display the localized name from now.运行程序,它应该从现在开始显示本地化名称。

Later edit: matter of fact, the name of the.mo file inside the /locale/xx/LC_MESSAGES/ path must match the name from the language = gettext.translation('test_l10n', locale_path, [current_locale] line in my code below, both of which can be chosen independently of the name of the.py file itself. Sorry if I've created confusion before.稍后编辑:事实上, /locale/xx/LC_MESSAGES/路径中的.mo 文件的名称必须与我下面代码中的language = gettext.translation('test_l10n', locale_path, [current_locale]行中的名称匹配, 两者都可以独立于 .py 文件本身的名称进行选择。抱歉,如果我之前造成了混乱。

This is my example file test_l10n.py:这是我的示例文件 test_l10n.py:

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

import datetime
import locale
import gettext

##

class l10nTest(object):
    def __init__(self, *args):
        pass

    def Main(self):
        self.get_datetime = datetime.datetime.today()
        self.weekday_now = self.get_datetime.weekday()
        self.temp = self.weekday_now + 1
        self.dayl = self.DayOfWeekLiteral(str(self.temp))

        print (_("Today is %s") % self.dayl)

    def DayOfWeekLiteral(self, dday):
        self.dday = dday
        if int(self.dday) == 1:
            self.dayl = _("Monday")
        if int(self.dday) == 2:
            self.dayl = _("Tuesday")
        if int(self.dday) == 3:
            self.dayl = _("Wednesday")
        if int(self.dday) == 4:
            self.dayl = _("Thursday")
        if int(self.dday) == 5:
            self.dayl = _("Friday")
        if int(self.dday) == 6:
            self.dayl = _("Saturday")
        if int(self.dday) == 7:
            self.dayl = _("Sunday")
        return self.dayl

##

if __name__ == "__main__":

    current_locale, encoding = locale.getdefaultlocale()
    # or it can be forced explicitly by uncomment the line below
#    current_locale = "pl"
    locale_path = './locale/'
    language = gettext.translation('test_l10n', locale_path, [current_locale])
    language.install()

    app = l10nTest(0)
    app.Main()

And this is my test_l10n.po file (in my case, for Romanian):这是我的 test_l10n.po 文件(在我的例子中,是罗马尼亚语):

# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
msgid ""
msgstr ""
"Project-Id-Version: \n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2021-02-02 22:08+0200\n"
"PO-Revision-Date: 2021-02-02 22:09+0200\n"
"Last-Translator: \n"
"Language-Team: \n"
"Language: ro\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"X-Generator: Poedit 2.4.2\n"

#: test_l10n.py:20
#, python-format
msgid "Today is %s"
msgstr "Azi este %s"

#: test_l10n.py:25
msgid "Monday"
msgstr "luni"

#: test_l10n.py:27
msgid "Tuesday"
msgstr "marți"

#: test_l10n.py:29
msgid "Wednesday"
msgstr "miercuri"

#: test_l10n.py:31
msgid "Thursday"
msgstr "joi"

#: test_l10n.py:33
msgid "Friday"
msgstr "vineri"

#: test_l10n.py:35
msgid "Saturday"
msgstr "sâmbătă"

#: test_l10n.py:37
msgid "Sunday"
msgstr "duminică"

Later edit: I forgot to mention: running the above example on my system (Windows 10, with the system locale set to Romanian), it gives:后来编辑:我忘了提:在我的系统上运行上面的示例(Windows 10,系统区域设置为罗马尼亚语),它给出:

(at the time I posted this answer) (在我发布这个答案时)

Azi este marți

(at the time I added this later edit, which is the next day already in terms of local time) (当时我添加了这个稍后的编辑,就当地时间而言已经是第二天了)

Azi este miercuri

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM