Odoo 12 num2words Количество текста

Я новичок в этом сообществе и настраиваю версию сообщества Odoo для своей маленькой компании. Я все делаю, просто не знаю, как настроить num2words для отображения общей суммы в отчетах по счетам!

Я нашел num2words api в res_currency.py в Base / Modules, но я провожу два дня, исследуя, как подключиться, и ничего. Что я должен унаследовать и как, а также что указывать в документе счета-фактуры qweb?

Я сделал такой модуль:

from num2words import num2words

class account_invoice(models.Model):
_inherit = "account.invoice"

 @api.multi
def amount_to_text(self, amount):
    self.ensure_one()
    def _num2words(number, lang):
        try:
            return num2words(number, lang=lang).title()
        except NotImplementedError:
            return num2words(number, lang='en').title()

if num2words is None:
        logging.getLogger(__name__).warning("The library 'num2words' is missing, cannot render textual amounts.")
        return ""

formatted = "%.{0}f".format(self.decimal_places) % amount
    parts = formatted.partition('.')
    integer_value = int(parts[0])
    fractional_value = int(parts[2] or 0)

    lang_code = self.env.context.get('lang') or self.env.user.lang
    lang = self.env['res.lang'].search([('code', '=', lang_code)])
    amount_words = tools.ustr('{amt_value} {amt_word}').format(
                    amt_value=_num2words(integer_value, lang=lang.iso_code),
                    amt_word=self.currency_unit_label,
                    )
    if not self.is_zero(amount - integer_value):
        amount_words += ' ' + _('and') + tools.ustr(' {amt_value} {amt_word}').format(
                    amt_value=_num2words(fractional_value, lang=lang.iso_code),
                    amt_word=self.currency_subunit_label,
                    )
    return amount_words

Получена такая ошибка:

Error to render compiling AST
AttributeError: 'NoneType' object has no attribute 'currency_id'
Template: account.report_invoice_document_with_payments
Path: /templates/t/t/div/p[1]/span
Node: <span t-if="doc.currency_id" t-esc="doc.currency_id.amount_to_text(doc.amount_total)"/>

В QWeb я написал следующее:

<span t-if="doc.currency_id" t-esc="doc.currency_id.amount_to_text(doc.amount_total)"/> 

Заранее спасибо!


person Uros Kalajdzic    schedule 29.11.2018    source источник


Ответы (2)


В вашем случае "currency_id" - это поле Many2one. Модель res.currency не содержит функцию класса amount_to_text.

Вы написали функцию amount_to_text в модели 'account.invoice'. Так что измени свой вот так,

<span t-if="doc.currency_id" t-esc="doc.amount_to_text(doc.amount_total)"/> 

ИЛИ (если в вашем объекте нет поля currency_id)

 <span t-if="doc.amount_to_text" t-esc="doc.amount_to_text(doc.amount_total)"/> 
person sfx    schedule 29.11.2018
comment
Я изменил QWeb на: ‹span t-if = doc.currency_id t-esc = doc.amount_to_text (doc.amount_total) /› и снова такая же ошибка - person Uros Kalajdzic; 29.11.2018
comment
В каком объекте у вас есть этот отчет? Если у вас нет поля currency_id, добавьте его в свою модель или используйте валюту компании (см. Мой отредактированный ответ) - person sfx; 29.11.2018
comment
Когда я помещаю новый код, теперь появляется ошибка: Ошибка при рендеринге компиляции AST AttributeError: объект 'NoneType' не имеет атрибута 'amount_to_text' - person Uros Kalajdzic; 29.11.2018

Пожалуйста, используйте приведенный ниже код

<span t-if="o.currency_id" t-esc="o.amount_to_text(o.amount_total)"/>

Вы получаете сообщение об ошибке, потому что в базовом отчете используется o вместо doc. см. приведенную ниже часть кода из базы.

<t t-foreach="docs" t-as="o">

Так что попробуйте использовать o вместо doc

person Anitha Das B    schedule 30.09.2019