Introduction
In this tutorial, we explore Odoo Controllers and Routes to display data on the website, and we explain every concept in clear, active language. We immediately dive into how to develop a simple Odoo website controller so you can understand the power of Odoo’s web routing features. Throughout this post, you will see the key phrases “Odoo Controllers and Routes” and many of its synonyms, such as “Odoo website controller” and “route configuration,” seamlessly integrated to help you grasp the topic at first glance. We begin by reviewing essential code segments and step-by-step instructions that guide you from setting up your development environment to customizing your routes for optimal data display. Additionally, we provide numerous examples, detailed explanations, and best practices to help you succeed. For more details on Odoo’s development framework, please visit the official documentation at Odoo Documentation.
Understanding Odoo Controllers and Routes
Firstly, let us clarify what Odoo controllers and routes are and why they matter. Controllers in Odoo act as the bridge between the user’s web request and the server-side logic. They receive HTTP requests, process them according to your business logic, and return an appropriate response. Routes, on the other hand, allow you to map specific URLs to their corresponding controller methods. Consequently, when a user visits a given URL, Odoo invokes the designated controller method to generate and return the necessary data. By mastering these concepts, you will quickly create engaging web pages and interactive applications with Odoo.
Furthermore, understanding the structure and format of Odoo controllers improves your ability to customize modules. In the following sections, we will break down every part of the controller code and demonstrate how you can modify and extend it to fit your unique needs.
Setting Up Your Odoo Development Environment
Before you start coding, you must set up your Odoo development environment. Initially, install the required Python dependencies, configure your PostgreSQL database, and download the latest stable version of Odoo from the official website. Always update your environment using the package manager to avoid conflicts with installed libraries.
Moreover, you need an Integrated Development Environment (IDE) that supports Python. We recommend Visual Studio Code or PyCharm because they offer excellent support for Python syntax, intelligent code completion, and version control integration. Once your system is ready, you can create a new Odoo module.
Scaffolding Your Odoo Module: od_openacademy_website
To illustrate our concepts, we will create a module named od_openacademy_website. This module serves as a scaffold for a website where you display courses, sessions, and other details. We begin by using Odoo’s scaffold command, which generates a simple module structure containing essential folders and files.
You can run the following command in your terminal:
$ odoo scaffold od_openacademy_website /path/to/your/addons
This command creates the folder structure and populates it with files like __init__.py, __manifest__.py, and additional folders for controllers, models, and views. Transitioning from module scaffolding to coding is smooth because the scaffolding command gives you a pre-defined structure that complies with Odoo’s guidelines.
Modifying the Manifest File
After scaffolding your module, the next step is modifying the manifest file (__manifest__.py). The manifest file tells Odoo the metadata about your module, such as its name, summary, dependencies, and installed assets. To illustrate, open the manifest file and review its contents:
{
'name': 'Odoo OpenAcademy Website',
'summary': 'A module to display courses and sessions on the website',
'description': 'This module demonstrates how to create controllers and routes to display data on the website using Odoo.',
'author': 'Your Name',
'depends': ['website'],
'data': [
# XML files for views, templates, etc.
],
'installable': True,
'application': True,
}
Additionally, you may add more dependencies if you plan to expand your module’s functionality. Always ensure the manifest is correct and free of syntax errors before proceeding.
Creating a Basic Controller in Odoo
Now, let’s create a basic controller that demonstrates how to display text data on your website. Transitioning from the manifest file, navigate to your module’s controller directory. Create a new Python file, for example, controllers/main.py.
Below is the sample code that we will explain in detail. This code forms the core of what you need to handle user requests and display data:
from odoo import http
class OdooDiscussions(http.Controller):
@http.route('/odoodiscussions/courses', auth='public', website=True)
def display_data(self, **kwargs):
return "This is Odoo Discussions"
Explanation
- Importing the Required Module:
The code starts by importing thehttpmodule from Odoo. This module provides the base classes for creating web controllers.
from odoo import http
- Defining the Controller Class:
A new class namedOdooDiscussionsis created, which inherits fromhttp.Controller. This setup allows Odoo to recognize this class as a controller.
class OdooDiscussions(http.Controller):
- Decorating the Route:
The@http.routedecorator defines the URL pattern for the controller. In this example, the URL/odoodiscussions/coursesis mapped to the methoddisplay_data. The parametersauth='public'andwebsite=Trueallow public access and designate this as a website route.
@http.route('/odoodiscussions/courses', auth='public', website=True)
- Defining the Method to Process Requests:
Thedisplay_datamethod processes the HTTP request and returns a simple string. When users navigate to the specified URL, this response appears on their screen.
def display_data(self, **kwargs):
return "This is Odoo Discussions"
In addition to this route, we also demonstrate another controller for handling sessions. See the following additional code block:
@http.route('/odoodiscussions/sessions', auth='public', website=True)
def display_sessions(self, **kwargs):
return "This is Odoo Discussions Sessions"
This segment resembles the previous one but handles a different URL. It demonstrates how you can create multiple endpoints easily by defining new methods within the same or different controller classes.
Detailed Explanation of Controller Code
Now that you have a basic controller, we discuss the code in greater detail. Transitioning through each part will build your understanding systematically.
Importing the HTTP Library
The line
from odoo import http
is crucial because it imports the framework’s HTTP functionalities. Without this module, you cannot access the controller class or the routing functionalities. Always check for proper import statements to ensure your controller functions as expected.
Controller Class Definition
When you define a class with:
class OdooDiscussions(http.Controller):
you instruct Odoo that this is a controller that can manage incoming HTTP requests. The class name OdooDiscussions is descriptive, immediately conveying that it deals with discussion-related data on your website.
Defining Routes with Decorators
Decorators in Python attach additional behavior to functions. In our controller, the decorators assign URL routes to the methods. For example:
@http.route('/odoodiscussions/courses', auth='public', website=True)
This line tells Odoo to monitor the specified URL. As users click or enter the URL, Odoo directs the requests to the display_data method. Transition words such as “furthermore” and “additionally” are used throughout code documentation, ensuring that explanations flow logically from one aspect to another.
Returning Data via Controller Methods
Inside the method display_data, the return value is a simple string:
return "This is Odoo Discussions"
This immediate feedback confirms that your route works. As you progress, you may modify this method to serve dynamic HTML content or integrate with data models. Remember that every controller method should complete the request-response cycle efficiently.
Route Configuration and Best Practices
In Odoo, configuring routes correctly is key to developing an intuitive website. Transitioning smoothly between routes and controllers ensures your site delivers a seamless user experience.
Creating Multiple Routes
For instance, the second code block illustrates a route for sessions:
@http.route('/odoodiscussions/sessions', auth='public', website=True)
def display_sessions(self, **kwargs):
return "This is Odoo Discussions Sessions"
Both routes allow unauthenticated access by setting auth='public'. Consequently, anyone can view the content, making it easy for you to share links on social media or embed them on external websites.
Setting the Website Parameter
The parameter website=True is crucial as it informs Odoo that the route should be integrated with the website module. Furthermore, it triggers additional processing to render the content in the website’s template. Transition periods in your code often feature the website=True flag to ensure consistency across your module.
Distributing Keyphrases Evenly
As you write or modify your controllers, keep in mind the importance of the keyphrase “Odoo Controllers and Routes.” Use this phrase and its synonyms uniformly in comments, code documentation, and blog posts. This consistent usage not only strengthens your SEO but also clarifies your topic for readers. For example, you may refer to your code comments by saying, “This method in our Odoo website controller handles route assignment,” or “We configure our route to display data on the website using Odoo’s framework.”
Displaying Data on the Website
Now that you understand the controller basics, let’s move on to displaying data on the website. Transitioning from a simple string output, you can enhance the method to show dynamic content by integrating models and templates.
Returning HTML from Controllers
Instead of returning plain text, you can return HTML. For example, modify the display_data method:
@http.route('/odoodiscussions/courses', auth='public', website=True)
def display_data(self, **kwargs):
html_content = """
<html>
<head>
<title>Odoo Courses</title>
</head>
<body>
<h1>Welcome to Odoo Discussions!</h1>
<p>This is a dynamic page generated by our Odoo website controller.</p>
</body>
</html>
"""
return html_content
Additionally, you can use Odoo’s templating engine to separate logic from presentation. By loading QWeb templates, you achieve a cleaner and more maintainable codebase. For example:
@http.route('/odoodiscussions/courses', auth='public', website=True)
def display_data(self, **kwargs):
return http.request.render('od_openacademy_website.course_template', {})
In the above snippet, replace 'od_openacademy_website.course_template' with the actual XML QWeb template ID. Odoo then automatically finds the template, processes it, and renders the final HTML.
Integrating Models and Data
To further enrich your website, you can couple your controller with Odoo models. This approach allows you to query the database for relevant records and pass that data to your template. For instance:
from odoo import http
from odoo.http import request
class OdooDiscussions(http.Controller):
@http.route('/odoodiscussions/courses', auth='public', website=True)
def display_data(self, **kwargs):
courses = request.env['openacademy.course'].sudo().search([]) # Query all courses
return request.render('od_openacademy_website.course_template', {'courses': courses})
In this code, the controller fetches all records from the openacademy.course model. The data then flows into a QWeb template, which cycles through and displays each course dynamically. Transition words such as “initially,” “subsequently,” and “finally” help make each step clear.
Adding Customizations and Enhancements
Once you grasp the basics of controllers and routes, you can extend your module with custom features. Transitioning from the simple examples above, you can add more methods, enhance your templates, and integrate AJAX calls or dynamic JavaScript implementations.
Advanced Route Parameters
You may also define routes with URL patterns that include dynamic parameters. For instance, consider the URL pattern /odoodiscussions/courses/<int:course_id>. This pattern directs the controller to process the course_id from the URL:
@http.route('/odoodiscussions/courses/<int:course_id>', auth='public', website=True)
def course_detail(self, course_id, **kwargs):
course = request.env['openacademy.course'].sudo().browse(course_id)
if not course:
return request.render('od_openacademy_website.course_not_found', {})
return request.render('od_openacademy_website.course_detail_template', {'course': course})
The active voice of the above function immediately informs you that when a user navigates to a specific course URL, the system fetches the course by its ID and renders the appropriate template. Transition words, such as “if not” and “otherwise,” make the function’s flow simple to follow.
Utilizing AJAX for Dynamic Content
You can also enhance your routes by incorporating JavaScript and AJAX. By using AJAX calls, you let the client-side dynamically update partials of the web page without refreshing the entire page. As an example, consider the following simplified controller method:
@http.route('/odoodiscussions/course_data', auth='public', website=True, type='json')
def get_course_data(self, **kwargs):
courses = request.env['openacademy.course'].sudo().search([])
course_data = [{'id': course.id, 'name': course.name} for course in courses]
return course_data
In this snippet, the method uses JSON to return the courses in a structured format. This structure benefits asynchronous page updates, and you can then use JavaScript on the frontend to render course data without reloading the page.
Troubleshooting Common Issues
While developing your Odoo website controller, you might encounter a few common issues. Transitioning to the troubleshooting section, let’s discuss how to diagnose and resolve these problems.
Issue 1: Route Not Found
If you navigate to your URL and see a 404 error, you should verify that:
- The module is correctly installed.
- The URL in the
@http.routedecorator exactly matches what you expect. - You have restarted the Odoo server after making changes.
For instance, if you made a typo in the route definition, the URL will not be accessible. Always check your logs for errors and warnings.
Issue 2: Permission Denied
If you get a permission error, confirm that you set auth='public' if the route should be available to all users. Alternatively, configure auth='user' and ensure appropriate user permissions are set. Additionally, check that the user has access rights via the Odoo security rules defined in ir.model.access.csv.
Issue 3: Template Rendering Errors
When your controller returns data via templates, ensure that:
- You have defined the correct QWeb template ID in the controller.
- Your XML view files are error-free.
- The template syntax follows Odoo’s standards.
Transition words like “furthermore” and “additionally” will help you remember to check associated module files for any required updates after changes in the controller.
Using Debugging Tools
Furthermore, leverage Odoo’s logging and debugging features. You can insert temporary log statements inside your controller methods:
import logging
_logger = logging.getLogger(__name__)
class OdooDiscussions(http.Controller):
@http.route('/odoodiscussions/courses', auth='public', website=True)
def display_data(self, **kwargs):
_logger.info("Display_data method called with kwargs: %s", kwargs)
return "This is Odoo Discussions"
The log messages will appear in your server logs and help pinpoint issues quickly.
Best Practices for Odoo Controllers and Routes
Adhering to best practices solidifies a maintainable code base. Below are guidelines that you should always follow:
- Keep Methods Concise and Focused:
Each controller method should handle one responsibility only. Transition from one task to another within the method should be smooth and logical. - Use Active Voice in Code Comments and Documentation:
Use direct language such as “fetch the record” instead of “the record is fetched” to improve clarity. - Consistently Use Key Phrases:
Place key phrases like “Odoo Controllers and Routes” in your comments, log messages, and documentation. This consistency reinforces the topic and improves search engine optimization (SEO). - Structure Code with Clear Sections:
Segment your code with comments and divisions. For example, separate route definitions from template rendering logic. - Utilize Odoo’s Security Model:
Always set appropriate authentication levels. For public routes, useauth='public'; for sensitive data, useauth='user'and secure your routes with user-specific access rights. - Document Your Code Thoroughly:
Write clear documentation and in-code comments that describe why decisions were made rather than only what the code does. Transition statements in comments enhance readability.
By following these practices, you ensure that your code remains easy to understand, maintain, and extend in the future.
Additional Resources and Next Steps
It is important to further your learning by consulting additional resources. For instance, the official Odoo Documentation offers in-depth guides on creating controllers and configuring routes. Furthermore, community forums, video tutorials, and Odoo’s GitHub repositories are excellent sources to learn advanced topics.
Videos and Tutorials
Consider watching video tutorials on platforms like YouTube that focus on Odoo development. These videos present practical examples and step-by-step instructions that complement the text-based tutorial provided here. For example, you might search for “Odoo 16 Controllers Tutorial” to see visual explanations of the techniques discussed.
Books and Courses
There are also several books and online courses available that walk you through building full-featured Odoo modules. These resources include:
- “Odoo Development Essentials”
- “Mastering Odoo Development”
- Online courses at Udemy or Odoo’s own training programs
Additionally, subscribing to Odoo-related newsletters and following specialist blogs helps you stay updated with the latest trends and best practices.
Community Contributions
Moreover, engage with the developer community on platforms like the Odoo Forum or on GitHub. Sharing your experiences and learning from others reinforces your coding skills and can help solve challenging issues more effectively.
Detailed Step-by-Step Example: Building a Complete Module
Let’s combine everything we have learned to build a complete module that displays courses and sessions on the website.
Step 1: Scaffold Your Module
Run the following command:
$ odoo scaffold od_openacademy_website /path/to/your/addons
This command creates the base structure with folders such as:
controllers/models/views/__init__.py__manifest__.py
Step 2: Update __manifest__.py
Edit the __manifest__.py file to include necessary metadata:
{
'name': 'Odoo OpenAcademy Website',
'summary': 'Display courses and sessions using Odoo Controllers and Routes',
'description': 'This module uses Odoo Controllers and Routes to display data on a website by leveraging Odoo’s built-in HTTP controller and templating engine.',
'author': 'Your Name',
'depends': ['website'],
'data': [
'views/course_templates.xml',
],
'installable': True,
'application': True,
}
This file tells Odoo all the information about your module, including its dependencies on the website module.
Step 3: Create Controller Files
In the controllers/ directory, create a file named main.py. Then add the following code:
from odoo import http
from odoo.http import request
import logging
_logger = logging.getLogger(__name__)
class OdooDiscussions(http.Controller):
@http.route('/odoodiscussions/courses', auth='public', website=True)
def display_data(self, **kwargs):
_logger.info("display_data called with kwargs: %s", kwargs)
courses = request.env['openacademy.course'].sudo().search([])
# Render the QWeb template with the courses data
return request.render('od_openacademy_website.course_template', {'courses': courses})
@http.route('/odoodiscussions/sessions', auth='public', website=True)
def display_sessions(self, **kwargs):
_logger.info("display_sessions called.")
sessions = request.env['openacademy.session'].sudo().search([])
# Render another QWeb template with sessions data
return request.render('od_openacademy_website.session_template', {'sessions': sessions})
Explanation
- Logging:
The code uses Python’sloggingto record when each method is called. This aids troubleshooting and ensures that you can track the flow of execution. - Fetching Data:
The controller fetches records from two models:openacademy.courseandopenacademy.session. You must define these models later in your module. - Template Rendering:
Therequest.render()function links your controller to a QWeb template (e.g.,course_templateorsession_template). This creates a separation between logic and presentation.
Step 4: Create QWeb Templates
In the views/ directory, create an XML file named course_templates.xml to define the HTML templates. For example:
<odoo>
<template id="course_template" name="Course Template">
<t t-call="website.layout">
<div class="container">
<h1>Our Courses</h1>
<t t-if="courses">
<ul>
<t t-foreach="courses" t-as="course">
<li>
<t t-esc="course.name"/> - <t t-esc="course.description"/>
</li>
</t>
</ul>
</t>
<t t-else="">
<p>No courses available.</p>
</t>
</div>
</t>
</template>
<template id="session_template" name="Session Template">
<t t-call="website.layout">
<div class="container">
<h1>Our Sessions</h1>
<t t-if="sessions">
<ul>
<t t-foreach="sessions" t-as="session">
<li>
<t t-esc="session.name"/> - <t t-esc="session.start_date"/>
</li>
</t>
</ul>
</t>
<t t-else="">
<p>No sessions scheduled.</p>
</t>
</div>
</t>
</template>
</odoo>
Explanation
- Template Inheritance:
The<t t-call="website.layout">statement uses the base website layout provided by Odoo. - Dynamic Data:
The templates use the<t t-foreach="...">directive to iterate through the list of courses or sessions and display them in a friendly format. - Conditional Display:
The templates include conditional statements (<t t-if>) to check if any records exist and display appropriate messages otherwise.
Step 5: Define Your Models (Optional but Recommended)
Even though our main focus is on controllers and routes, a complete module typically defines models. Create a file in the models/ directory, naming it openacademy.py. Add the following code:
from odoo import models, fields
class Course(models.Model):
_name = 'openacademy.course'
_description = 'Course'
name = fields.Char(string='Course Name', required=True)
description = fields.Text(string='Course Description')
class Session(models.Model):
_name = 'openacademy.session'
_description = 'Session'
name = fields.Char(string='Session Name', required=True)
start_date = fields.Date(string='Start Date')
course_id = fields.Many2one('openacademy.course', string='Course')
Explanation
By defining models, you allow your controller methods to retrieve real data from the database. These models use standard Odoo fields, and the relationships between courses and sessions are straightforward.
Step 6: Update __init__.py Files
Make sure that your module initializes the controllers and models correctly. In your module’s root __init__.py, include:
from . import controllers
from . import models
And in the controllers/__init__.py file, include:
from . import main
Similarly, update the models/__init__.py if necessary.
Step 7: Restart Odoo and Install Your Module
After making these changes, restart your Odoo server to load your new module. Then, navigate to the Apps menu in Odoo, update the module list, and install Odoo OpenAcademy Website. Transitioning to testing, check the following URLs on your running Odoo instance:
- For courses:
http://your-odoo-domain/odoodiscussions/courses - For sessions:
http://your-odoo-domain/odoodiscussions/sessions
If everything functions as expected, you will see your dynamic templates rendered with data from your models.
Troubleshooting Advanced Issues
In some cases, after deploying your module, you may face challenges such as:
- Incorrect Data Rendering:
Ensure that your model records exist in the database. You might insert sample data manually or via an XML data file. - Template Incompatibility:
Verify that the template IDs in your controller match those defined in the XML files exactly. - Server Log Errors:
Always inspect the server logs for error messages. They often provide clear direction on what is wrong—be it a syntax error, access violation, or missing dependency.
Additionally, remember that your development cycles must include testing. Actively test each new route by adding sample data and then verifying the output in your browser.
Best Practices Recap and Tips
To summarize and reinforce the main points about Odoo Controllers and Routes, keep these best practices in mind as you develop your modules:
- Use Active Voice:
Write your controllers so that each line of code actively retrieves data, processes it, and renders a view. - Implement Clear Transitions:
Use transitions like “firstly,” “next,” and “finally” to collect and structure code and documentation logically. - Distribute Keyphrases Evenly:
Ensure the key phrases “Odoo Controllers and Routes” and their synonyms appear throughout your documentation, especially in your introduction and headings. - Keep Code Modular:
Do not mix business logic with presentation logic. Instead, keep controllers focused on data retrieval and use QWeb templates for rendering HTML. - Leverage Odoo’s Security:
Use proper authentication flags to protect sensitive data and define clear access control rules. - Document Thoroughly:
Add comments to your code blocks to explain why functionality was implemented in a particular way. This habit benefits both your debugging process and your future self or colleagues. - Embrace Simplicity:
Write clean, short functions that perform one clear task. Avoid redundancy and overly complex logic by using helper functions when necessary.
Next Steps and Further Customizations
After you complete this tutorial, consider extending your module in the following ways:
- Advanced Filtering and Search:
Implement URL parameters that allow users to search and filter courses by categories, dates, or keywords. - Dynamic User Interaction:
Integrate AJAX calls to load additional data on page scroll or via button clicks. Enhance the website user experience without requiring full page reloads. - Enhanced Security and User-Specific Content:
Configure authentication rules so that logged-in users can see personalized content. Implement access rights to allow administrators to edit course and session data on the fly. - Custom CSS and JavaScript:
Create custom static files (CSS and JS) within your module to improve the visual appearance and interactivity of your pages. - Template Inheritance:
Explore advanced QWeb templating techniques by inheriting from base templates and overriding specific blocks, which helps maintain a consistent look and feel on your website.
Transitioning to the next level of development will enable you to build complex and fully-featured web applications with Odoo.
Outgoing Links and Additional Resources
For deeper insights into Odoo’s architecture, routes, and website development, the following resources will prove invaluable:
- Odoo Official Documentation
This link leads to the comprehensive documentation for Odoo, which covers underlying principles and examples. - Odoo Developer Tutorials on GitHub
Explore the Odoo GitHub repository for real-world examples and community contributions. - Odoo Forum – Developer Section
Join the discussion forums to ask questions and share knowledge with fellow Odoo developers.
By exploring these resources, you will enhance your practical skills and stay up-to-date with the latest Odoo improvements and best practices.
Conclusion
In conclusion, this tutorial has guided you through the fundamental concepts of Odoo Controllers and Routes. You learned how to set up your development environment, scaffold an Odoo module, modify the manifest file, create a controller with multiple routes, and render dynamic web pages using QWeb templates. You also discovered best practices, troubleshooting tips, and advanced customizations that will help you further harness the power of Odoo’s web framework.
Remember, every transition in your code—from fetching data to rendering templates—must be clear and efficient. By following the active-voice methodology and keeping your key phrases distributed evenly, you can write maintainable, scalable modules that deliver a seamless user experience.
As you build more complex modules, continuously refer back to the concepts of controller logic, route configuration, and best practices described in this guide. With consistent practice and ongoing learning, you will quickly become proficient in crafting dynamic Odoo applications that display data effectively on your website.
We hope this comprehensive guide has provided you with a solid foundation and inspired you to explore further customizations. Happy coding, and may your Odoo development journey be both productive and enjoyable!
For any further questions or detailed examples, please refer again to the Odoo Official Documentation and join the community forums for support.
By following the steps and guidelines outlined in this tutorial, you now have a complete understanding of building robust Odoo modules using controllers and routes. Each section has been crafted to improve readability, using clear, active language and transitional words to bridge each concept together. Enjoy implementing these techniques in your next Odoo project, and keep experimenting with new features to create even more interactive and data-driven websites.
Happy coding!
This article detailed every aspect of Odoo Controllers and Routes for displaying data on the website. You can use the included code samples in your projects and modify them to suit your specific requirements. For a continuous learning journey, bookmark this page and revisit the best practices discussed here frequently.
Discover more from teguhteja.id
Subscribe to get the latest posts sent to your email.



