如何在Odoo中限制用户修改billing_notice模块的boolean字段?
Odoo:仅指定用户可修改boolean字段的权限控制示例
针对你在billing_notice模块中需要限制仅user1能修改boolean验证字段的需求,以下是两种可行的实现方案:
方案1:通过权限组+字段权限配置(XML)
这种方式是Odoo标准的权限控制逻辑,通过创建专属权限组并关联字段写入权限来实现:
<!-- 1. 创建仅用于修改verify字段的权限组 --> <record id="group_billing_notice_edit_verify" model="res.groups"> <field name="name">Billing Notice: Edit Verify Field</field> <field name="category_id" ref="base.module_category_access_rights"/> </record> <!-- 2. 给该组分配verify字段的写入权限 --> <record id="access_billing_notice_verify_write" model="ir.model.fields.access"> <field name="name">billing_notice.verify.write</field> <field name="model_id" ref="model_billing_notice"/> <field name="field_id" ref="billing_notice.field_billing_notice_verify"/> <field name="group_id" ref="group_billing_notice_edit_verify"/> <field name="perm_read" eval="True"/> <field name="perm_write" eval="True"/> <field name="perm_create" eval="False"/> <field name="perm_unlink" eval="False"/> </record> <!-- 3. 将user1添加到该权限组 --> <record id="user1_assign_verify_group" model="res.users"> <field name="id" ref="base.user_user1"/> <!-- 替换为user1的实际XML ID --> <field name="groups_id" eval="[(4, ref('group_billing_notice_edit_verify'))]"/> </record>
注意事项:
- 替换
base.user_user1为你系统中user1的实际XML ID(如果是自定义用户,使用创建用户时的ID)。 billing_notice.field_billing_notice_verify需替换为你的boolean字段正确的XML ID,格式为模块名.field_模型名_字段名。user2、user3只要不在该权限组内,就只能查看该字段,无法修改。
方案2:通过Python代码动态控制权限
如果你需要更灵活的逻辑,可以通过代码直接拦截字段修改操作:
方式A:字段级动态设置只读
from odoo import models, fields class BillingNotice(models.Model): _name = 'billing.notice' _description = 'Billing Notice' # 动态判断当前用户是否为user1,非user1则字段只读 verify = fields.Boolean( string='Verify', readonly=lambda self: self.env.user.id != self.env.ref('base.user_user1').id )
方式B:重写write方法拦截修改
from odoo import models, fields, api, exceptions class BillingNotice(models.Model): _name = 'billing.notice' _description = 'Billing Notice' verify = fields.Boolean(string='Verify') def write(self, vals): # 检查是否修改了verify字段,且当前用户不是user1 if 'verify' in vals and self.env.user.id != self.env.ref('base.user_user1').id: raise exceptions.AccessError("无权修改该验证字段") return super(BillingNotice, self).write(vals)
注意事项:
- 同样需要替换
base.user_user1为user1的实际XML ID。 - 方式A会让字段对非user1显示为只读;方式B则是在用户尝试修改时直接抛出权限错误,可根据交互需求选择。
内容的提问来源于stack exchange,提问作者odoo newbie
相关产品推荐
相关产品推荐

