Odoo 16中通过XPath实现自定义字段仅对非管理员用户设为只读的方法咨询
Odoo 16中通过XPath实现自定义字段仅对非管理员用户设为只读的方法咨询
我来帮你解决这个问题~你的需求是让自定义字段recommanded_price对非管理员用户设为只读(所有人都能看到字段,仅权限不同),但你的两种写法都存在小问题,下面给你梳理并给出正确方案:
先说说你之前写法的问题:
初始代码的问题:
你用了groups="base.group_system",这个属性的作用是只有管理员组的用户才能看到这个字段,非管理员完全看不到,这和你“字段可见但非管理员只读”的需求不符。尝试的attrs写法问题:
你写的attrs="{'readonly': [('groups', 'not in', ['base.group_system'])]}"是错误的,因为groups并不是product.template模型的字段,Odoo的attrs条件只能基于当前模型的字段值判断,不能直接引用用户组属性。
正确的实现方式
要判断当前用户是否属于管理员组,我们需要用Odoo内置的user_has_group()函数,直接在字段的readonly属性里写判断逻辑即可,代码如下:
<odoo> <data> <record id="product_template_only_form_view" model="ir.ui.view"> <field name="name">product.template.product.form</field> <field name="model">product.template</field> <field name="inherit_id" ref="product.product_template_only_form_view"/> <field name="arch" type="xml"> <xpath expr="//group[@name='group_general']" position="inside"> <field name="recommanded_price" string="Recommended Price" readonly="not user_has_group('base.group_system')" /> </xpath> </field> </record> </data> </odoo>
代码解释
user_has_group('base.group_system'):这个函数会检查当前登录用户是否属于管理员组(base.group_system是Odoo内置的管理员组标识)。not user_has_group(...):取反后,当用户不是管理员时,readonly为True(字段只读);当用户是管理员时,readonly为False(可编辑)。- 这样所有用户都能看到这个字段,权限区分仅体现在是否可编辑上,完全符合你的需求。
备注:内容来源于stack exchange,提问作者Vidurath Auchraje




