How to Implement self.env.ref() in Odoo?
What is self.env.ref()?
self.env.ref() is a method used in Odoo to retrieve a specific record using its external XML ID (also known as xml_id or record reference).
This is commonly used to access static records such as:
- Views
- Actions
- Security groups
- Email templates
- Configuration parameters
- Company data
✅ Syntax
record = self.env.ref('module_name.xml_id')
- module_name.xml_id must be a valid external ID defined in XML/CSV files.
Returns: A recordset of the referenced object (e.g., a group, template, etc.)
📌 Realistic Use Cases in Odoo
1. Get an Email Template and Send Email
template = self.env.ref('sale.email_template_edi_sale')
template.send_mail(self.id, force_send=True)
Used in workflows to send automated emails from a predefined template.
2. Add User to a Group via XML ID
group = self.env.ref('base.group_user') # Internal User group
user = self.env.user
user.write({'groups_id': [(4, group.id)]})
Used in user role assignment during custom onboarding flows or wizards.
3. Load a Custom View or Action
form_view = self.env.ref('sale.view_order_form')
return {
'type': 'ir.actions.act_window',
'name': 'Sales Order',
'res_model': 'sale.order',
'view_mode': 'form',
'view_id': form_view.id,
'target': 'current',
}
Used in buttons or server actions to open specific views.
4. Access Configuration Parameter or Company Record
company = self.env.ref('base.main_company')
print(company.name)
Helpful when performing actions that require company context.
⚠️ Common Errors
- KeyError: Raised if the XML ID does not exist.
- Best practice: Use self.env.ref() only when the XML ID is guaranteed to exist.
To avoid crashes in uncertain contexts, use:
record = self.env.ref('module.xml_id', raise_if_not_found=False)
✅ Summary Table
Method | Purpose | Use Case |
self.env.ref() | Fetch record by XML ID | Email templates, groups, views, etc. |
raise_if_not_found | Optional flag to suppress error | Safer lookups |