Odoo 11 QWeb模板中使用math.ceil报错的技术求助
The error you're hitting occurs because Python's math module isn't available in the default QWeb template context. When you tried to set Math to math, you ended up with a None value—hence the AttributeError when calling .ceil(). Let's walk through two solid fixes for this:
Option 1: Use Odoo's Built-in float_round Function (Template-Only Fix)
Odoo provides a float_round helper directly in QWeb that supports upward rounding, which matches exactly what math.ceil() does. This lets you fix the issue without touching any Python backend code:
<xpath expr="//*[@id='wrap']/section[2]/div" position="replace"> <!-- Calculate the ceiling value using Odoo's native function --> <t t-set="ceil_num" t-value="float_round(number_of_device_issue/2, precision_digits=0, rounding='UP')"/> <!-- Loop using the precomputed ceiling value --> <t t-foreach="range(0, ceil_num)" t-as="num"> <t t-esc="num"/> </t> </xpath>
The rounding='UP' parameter ensures we round up to the nearest integer, replicating the behavior of math.ceil() perfectly.
Option 2: Precompute the Value in Python (Backend Fix)
If you prefer handling calculations in your backend (ideal for complex logic or reusable code), compute the ceiling value in your model or controller and pass it to the template context:
Step 1: Add the calculation to your model (example)
import math from odoo import models, fields class YourModel(models.Model): _name = 'your.model.name' number_of_device_issue = fields.Integer(string="Device Issues") def get_ceil_device_issues(self): # Calculate ceiling of half the issue count return math.ceil(self.number_of_device_issue / 2)
Step 2: Use the precomputed value in QWeb
<xpath expr="//*[@id='wrap']/section[2]/div" position="replace"> <t t-foreach="range(0, record.get_ceil_device_issues())" t-as="num"> <t t-esc="num"/> </t> </xpath>
If you're rendering the template from a controller, pass the value directly in the context instead:
import math from odoo import http class YourController(http.Controller): @http.route('/your/route', auth='user') def your_route(self): number_of_device_issue = 5 # Replace with your actual value ceil_num = math.ceil(number_of_device_issue / 2) return http.request.render('your_module.your_template', { 'ceil_num': ceil_num, # Other context variables... })
Then use ceil_num in your template loop just like in Option 1.
Why Your Original Code Failed
QWeb templates don't have access to Python's standard library modules (like math) by default. When you tried <t t-set="Math" t-value="math"/>, the template context didn't recognize math, so it set Math to None—leading to the error when you tried to call Math.ceil().
内容的提问来源于stack exchange,提问作者Sachin Burnawal

