【问题标题】:Call a python function from template odoo 8从模板odoo 8调用python函数
【发布时间】:2016-08-19 07:03:23
【问题描述】:

我的控制器类中有一个函数,我需要在我的一个模板中调用该函数。我试过这个:

controller.py

class MyController(http.Controller):
    @http.route(["/myPath/"], type='http', auth="public", website=True)
    def myfucntion(self):
        -- something ---
    def thisMethod(self):
        I need to call this methd in remplate

template.xml

<t t-esc="thisMethod()"/>

得到错误:

 QWebException: "'NoneType' object is not callable" while evaluating

thiMethod()

这个方法怎么调用?

【问题讨论】:

  • 你必须提供一个实例:someinstance.thisMethod()
  • 如何为控制器类创建对象?

标签: templates controller web odoo-8 qweb


【解决方案1】:

据我了解,您实际上并没有使用 t-esc 语法从模板中调用该方法。您可以做的是在您的控制器中创建可通过 post 访问或获取请求的方法。如果您愿意,您可以使用 javascript 从您的模板中发出这些请求,或者通过标签将 javascript 文件包含在您的模板中。如果脚本很简单,您可能会使用内联 javascript

  <script>console.log("Hello World")</script> 

否则,您可以像这样指向静态目录中的 js 文件。

  <script src="/<module>/static/main.js"></script>

然而,Odoo 有一些包含 js 的规则。如果您使用 Odoo CMS 作为 Qweb 模板的父模板,那么您可能还想使用 xpath 将您的 js 文件与 Odoo 的所有其他 js 文件一起放置。

  <template id="my_js" inherit_id="website.assets_frontend" name="My Js">
      <xpath expr="script[last()]" position="after">
          <script type="text/javascript" src="/<module>/static/main.js" />
      </xpath>
  </template>

在 Odoo9 中,事情变得(可能)更复杂,因为您需要使用 require js 语法来在您的 js 中使用 post 请求。这是一个在 Odoo8 中应该工作的过度简化的示例。对于 Odoo9,请查看代码中使用 require js 的其他示例。

这里有一些控制器方法,一个是 json,另一个是 http。将您的代码放在适合您的地方。您可以选择返回更合适的内容(例如某些数据),但表示成功或失败的 True 或 False 可能就足够了。

    @http.route('/test/json/method/', auth='none', type='json', website=True)
    def test_json(self):
        #YOUR CODE HERE 
        return json.dumps({'json':True})

    @http.route('/test/http/method/', auth='none', type='http', website=True)
    def test_http(self):
        #YOUR CODE HERE
        return json.dumps({'http':True})

使用上述方法之一(简要)放置此 javascript,以在您的模板中调用该方法。

        <script>
        jQuery.get('/test/http/method/',function(data){ console.log( "HTTP RESPONSE: " + data ) });
        </script>
        <script>
    jQuery.ajax({
        type: "POST",
        url: '/test/json/method/',
        dataType: 'json',
        async: true,
        data: JSON.stringify({}),
        contentType: "application/json; charset=utf-8",
        success: function ( data ) {
           console.log( "JSON RESPONSE: " + JSON.stringify( data ) );
        },
        failure: function( data ){
           console.log( JSON.stringify( data ) );
        }
    })
    </script>

关于 Odoo 中的路由,有很多东西需要学习。有安全问题,你应该小心的权限问题。

https://www.odoo.com/documentation/8.0/howtos/website.html 讨论了一些概念的快速概述。 https://www.odoo.com/documentation/8.0/reference/http.html 讨论控制器。 https://www.odoo.com/documentation/8.0/reference/javascript.html 涵盖了 JavaScript。除此之外,请查看网络、控制器目录中的网站插件以获取更多示例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-31
    • 2021-02-25
    • 1970-01-01
    • 2016-02-29
    • 2021-09-20
    • 2010-12-22
    相关资源
    最近更新 更多