Skip to content
Home » Odoo Controllers and Routes: Add Webpage Support

Odoo Controllers and Routes: Add Webpage Support

  • Odoo

Introduction to Odoo Controllers and Routes

Odoo Controllers and Routes empower you to build dynamic web pages and add website support to your custom modules in Odoo 16. In this tutorial, we demonstrate how you can use Odoo Controllers and Routes to customize your website, integrate dynamic content, and render your custom QWeb templates. We start by setting up the environment, then proceed to create a QWeb template, build a controller to render your webpage, and finally customize the layout further. Throughout this guide, we use clear active voice and smooth transitions to help you build your knowledge step by step. Additionally, we practice key SEO techniques by maintaining a consistent keyphrase distribution related to Odoo Controllers and Routes.

For more information on Odoo’s best practices, please visit the Odoo Documentation.


Setting Up Your Odoo Environment

Before you add website support to your custom webpage, you must prepare your development environment. First, install the latest Odoo 16 instance along with all necessary dependencies. You must install Python, PostgreSQL, and your favorite Integrated Development Environment (IDE) such as Visual Studio Code or PyCharm.

Prerequisites and Installation

  1. Install Odoo 16:
    Ensure you download and install Odoo 16 from the official website or via your package manager. This installation enables you to test your controllers and templates immediately.
  2. Configure Database:
    Set up PostgreSQL and create a database for your Odoo instance. Update your Odoo configuration file to include the database parameters.
  3. Set Up Custom Module Structure:
    Create a directory for your custom module. Use the following scaffold command to generate the basic structure if needed:
   odoo scaffold my_custom_module /path/to/addons

This command creates folders for controllers, models, views, security, and static files.

  1. Restart Odoo and Update Modules:
    After setting up your environment, restart Odoo and update the module list using:
   ./odoo-bin -c /path/to/odoo.conf -u my_custom_module

This command ensures that both your new module and any customizations are loaded correctly.

With your environment properly configured, you are ready to customize your webpage using Odoo Controllers and Routes.


Creating a Custom QWeb Template for Webpage Support

The QWeb templating engine in Odoo allows you to create dynamic webpages that integrate seamlessly with your backend data. In this tutorial, we design a custom QWeb template that supports dynamic data, such as course information and messages that update automatically.

Template Structure and Dynamic Content

Below is the complete QWeb template code that we use to add website support to a custom webpage:

<template id="odoodiscussions_classess" name="Odoo Discussions Classes">
    <t t-call="website.layout">
        <title>Odoo Discussions</title>
        <h2><span t-esc="message"/></h2>
        <ul>
            <t t-foreach="courses" t-as="course">
                <li>[<span t-esc="course.code"/>] <span t-esc="course.name"/></li>
            </t>
        </ul>
    </t>
</template>

We explain each part of this template as follows:

  1. Template Definition:
    The template is defined with the ID odoodiscussions_classess and the name “Odoo Discussions Classes”. This ID is crucial because the controller references it during rendering.
  2. Inheriting the Website Layout:
    By using <t t-call="website.layout">, the template inherits the standard Odoo website structure. This inclusion ensures that your page maintains consistency with the look and feel of the rest of your site.
  3. Dynamic Title and Message:
    The <title> tag sets the browser title to “Odoo Discussions”. The <h2> tag uses <span t-esc="message"/> to display a dynamic message passed from the controller.
  4. Looping Through Dynamic Data:
    The code <t t-foreach="courses" t-as="course"> iterates over a list of courses, displaying each course’s code and name dynamically. This approach highlights the power of dynamic data integration using Odoo Controllers and Routes.

Each code block is active and clear, and we utilize direct, simple language to maintain readability. Next, we build the controller that passes this dynamic data to the template.


Building the Controller to Render Your Custom Webpage

The controller in Odoo manages HTTP requests and links your backend logic with your QWeb templates. Below is the controller code used to fetch course data and render the custom webpage:

from odoo import http
from odoo.http import request

class OdooDiscussions(http.Controller):

    @http.route('/odoodiscussions/classes', auth='public', website=True)
    def odoodiscussions_classes(self, **kwargs):
        courses = request.env['od_openacademy.course'].search([])
        values = {
            "message": "Hello Odoo Discussions",
            "courses": courses
        }
        return request.render('odoodiscussions_classess', values)

Let’s break down this code step by step:

  1. Importing Required Modules:
    The controller imports the http module and the request object from Odoo. These imports are vital to handling web requests and interacting with the Odoo environment.
  2. Defining the Controller Class:
    The class OdooDiscussions inherits from http.Controller, which tells Odoo that this class contains web-facing endpoints.
  3. Setting Up the Route:
    The @http.route decorator sets the URL endpoint /odoodiscussions/classes for this controller method. The parameters auth='public' and website=True ensure that the route is accessible to all users and integrated with the website module, respectively.
  4. Fetching Dynamic Data:
    Inside the method odoodiscussions_classes, the controller queries the model od_openacademy.course to fetch all course records. It then creates a dictionary values that contains a dynamic message and the list of courses.
  5. Rendering the Template:
    Finally, the controller calls request.render('odoodiscussions_classess', values) to render the custom QWeb template. The dynamic data in the values dictionary is then available in the template for display.

This controller code actively drives the flow of data from your backend to the frontend, ensuring that your webpage always displays the most current information.


Integrating Website Layout and Dynamic Data

After you build your QWeb template and controller, the next step is to integrate the template into the overall website layout and ensure that dynamic data is correctly displayed. This section explains how the integration works and offers tips to ensure smooth customization.

Dynamic Data Flow and Message Display

When a user visits the URL /odoodiscussions/classes, the following steps occur:

  1. URL Request:
    The browser sends a request to the defined URL. Odoo intercepts this request and directs it to the odoodiscussions_classes controller method.
  2. Data Query:
    The controller executes the dynamic data query, fetching records from the od_openacademy.course model. It then creates a dictionary containing a welcome message (in this case, “Hello Odoo Discussions”) and a list of courses.
  3. Template Rendering:
    The controller then renders the QWeb template odoodiscussions_classess and passes the dynamic data dictionary as context. The template inherits Odoo’s website layout and dynamically displays the welcome message and list of courses.
  4. Final Output:
    The browser receives the fully rendered webpage, which displays the dynamically generated content. Users see the message and the course list with each course’s code and name.

Using clear active language and transitional phrases like “first,” “next,” and “finally,” you can easily follow the data flow from the controller to the template. This approach demonstrates how Odoo Controllers and Routes enable dynamic website customization.


Advanced Customizations for Website Support

Once you master the basics, you can extend your module by adding advanced customizations. In this section, we explore additional techniques to further enhance website support and display.

Adding Dynamic Menus, Headers, and Footers

You can further enrich your Odoo website using Odoo Controllers and Routes by adding dynamic menus, headers, and footers. For example, you can modify your QWeb template to include additional sections:

<template id="odoodiscussions_classess" name="Odoo Discussions Classes">
    <t t-call="website.layout">
        <title>Odoo Discussions</title>
        <header>
            <h1>Welcome to Our Course Discussions</h1>
        </header>
        <section>
            <h2><span t-esc="message"/></h2>
            <ul>
                <t t-foreach="courses" t-as="course">
                    <li>[<span t-esc="course.code"/>] <span t-esc="course.name"/></li>
                </t>
            </ul>
        </section>
        <footer>
            <p>For more details, visit our <a href="https://www.odoo.com/documentation" target="_blank">Odoo Documentation</a>.</p>
        </footer>
    </t>
</template>

In this enhanced template, you actively add:

  • A header section that welcomes visitors.
  • A footer with a link to the official Odoo Documentation.
  • An organized structure that splits content into logical sections of header, main section, and footer.

Customizing the Controller for Enhanced Performance

You can customize your controller code to improve performance by adding logging and error handling. For example, update your controller to include logging:

from odoo import http
from odoo.http import request
import logging

_logger = logging.getLogger(__name__)

class OdooDiscussions(http.Controller):

    @http.route('/odoodiscussions/classes', auth='public', website=True)
    def odoodiscussions_classes(self, **kwargs):
        try:
            courses = request.env['od_openacademy.course'].search([])
            values = {
                "message": "Hello Odoo Discussions",
                "courses": courses
            }
            _logger.info("Successfully fetched courses")
            return request.render('odoodiscussions_classess', values)
        except Exception as e:
            _logger.error("Error fetching courses: %s", e)
            return request.render('website.404')

This code actively logs every step for easier debugging and graceful error handling. Such modifications improve the reliability of your module and demonstrate the flexibility of Odoo Controllers and Routes in real-world applications.


Step-by-Step Walkthrough of the Code

To reinforce your understanding, let’s walk through the key portions of our code step by step.

QWeb Template Walkthrough

  1. Template Start:
    The template opens with the declaration:
   <template id="odoodiscussions_classess" name="Odoo Discussions Classes">

This line establishes the template’s identity. The ID is used by the controller for rendering.

  1. Inheritance of Layout:
    The <t t-call="website.layout"> tag includes the website layout, ensuring the page adheres to Odoo’s design. This action automatically integrates common elements like navigation menus and footers.
  2. Dynamic Title and Message:
    The <title> tag sets the page title, while <h2><span t-esc="message"/></h2> displays a customizable message. When the controller passes the message “Hello Odoo Discussions,” it shows up here.
  3. Looping Over Data:
    The <t t-foreach="courses" t-as="course"> block iterates over the courses. For each course, it builds a list item showing the course code and name:
   <li>[<span t-esc="course.code"/>] <span t-esc="course.name"/></li>

This dynamic looping transforms raw data into a readable list.

  1. Template End:
    Finally, the template closes by ending the layout tag:
   </t>
   </template>

This orderly structure ensures that all dynamic data and page layout items are rendered correctly.

Controller Code Walkthrough

  1. Importing Modules:
    The controller imports the necessary modules to handle HTTP requests:
   from odoo import http
   from odoo.http import request

These modules provide essential functions for request handling.

  1. Class Definition:
    The class OdooDiscussions extends http.Controller, making it recognizable to Odoo’s web system.
  2. Defining the Route:
    The @http.route decorator specifies that the URL /odoodiscussions/classes maps to the function odoodiscussions_classes. This path is accessible to all users through auth='public' and integrates with the website through website=True.
  3. Data Query and Dictionary Creation:
    Within the function, the controller queries the courses using:
   courses = request.env['od_openacademy.course'].search([])

It then builds a dictionary values containing a dynamic message and the courses list.

  1. Rendering the Template:
    The controller returns the rendered template by calling:
   return request.render('odoodiscussions_classess', values)

The dynamic data is thus passed to the QWeb template for display.

This detailed walkthrough clarifies the connection between your backend logic and the frontend display, ensuring that every element works together to create a dynamic, interactive webpage.


Troubleshooting and Debugging Tips

Even with careful coding, you may encounter issues. Here are some troubleshooting tips to keep your development process smooth:

  1. Template Not Rendering:
    First, ensure that the template ID in the controller matches exactly with the ID in your QWeb template. Check for any typos or extra spaces.
  2. Data Not Appearing:
    Next, verify that the model od_openacademy.course contains records. You can manually add data through the Odoo backend or test using Odoo shell commands.
  3. Controller Errors:
    Then, use logging statements to catch errors. If you see a log entry for errors retrieving courses, check your model definitions and access rights.
  4. Access Issues:
    Finally, ensure that the auth parameter in the route is set correctly. If the page does not display for public users, try setting auth='user' to diagnose the issue.

These active troubleshooting steps help you identify and fix problems rapidly while reinforcing your understanding of Odoo Controllers and Routes.


Best Practices for Odoo Website Customization

When developing with Odoo Controllers and Routes, consider the following best practices:

  1. Maintain a Modular Structure:
    Organize your code by separating controllers, views, and models. This approach makes your module easier to maintain and extend.
  2. Use Active Voice Everywhere:
    Document your code using active voice. For example, write “the controller fetches data” rather than “data is fetched by the controller.”
  3. Incorporate Clear Transition Words:
    Use transition words such as “first,” “next,” and “finally” throughout your documentation and comments. This thoroughness improves readability and clarity.
  4. Continuously Test Your Changes:
    Regularly restart your Odoo server and update your module list to test modifications. This active approach prevents errors from accumulating in the codebase.
  5. Leverage Documentation Links:
    Embed useful links such as the Odoo Documentation and your GitHub commit history (e.g., Commit Details) within your code comments and documentation for quick reference.

By following these best practices, you build a more robust, maintainable module that leverages the full power of Odoo Controllers and Routes.


Advanced Topics in Website Customization

After you have mastered the basics, you can extend your custom webpage functionality further. Here are some advanced topics to explore:

Implementing AJAX for Real-Time Updates

You can add AJAX calls to update webpage content dynamically without a full reload. For instance, create an additional route that returns JSON data, and use JavaScript to fetch and update the data on the frontend.

Customizing the Website Layout Further

Integrate custom CSS and JavaScript files to create a truly unique user experience. Place your custom static files in the static directory and reference them in your QWeb template as follows:

<template id="assets_custom" inherit_id="website.assets_frontend">
    <xpath expr="." position="inside">
        <link rel="stylesheet" href="/my_custom_module/static/src/css/custom.css"/>
        <script type="text/javascript" src="/my_custom_module/static/src/js/custom.js"></script>
    </xpath>
</template>

This integration allows you to modify the appearance and interaction models of your custom webpage actively.

Enhancing Security and Access Control

Refine access control by adjusting the auth parameters in your routes and updating the ir.model.access.csv file. Active management of user access ensures that sensitive data remains secure while providing necessary functionality to the public.

Linking with Other Modules

Consider integrating your module with other Odoo modules. For example, you can connect your course management module with eLearning or CRM modules to provide a seamless experience across your business applications.


Conclusion and Next Steps

In conclusion, this tutorial has shown you step by step how to use Odoo Controllers and Routes to add website support to a custom webpage in Odoo 16. We explored the basics of setting up your environment, creating a dynamic QWeb template, building a robust controller, and integrating dynamic content. Moreover, we discussed advanced customizations and troubleshooting tips that help you maintain a secure and efficient module.

By following the active instructions and clear explanations provided in this guide, you can confidently build and extend your own modules. Remember to test your code frequently, adhere to best practices, and consult additional resources when necessary.

Next, you can explore other advanced topics such as AJAX integration, extensive CSS/JS customization, and module interoperability with other Odoo applications. This continuous practice will help you master Odoo Controllers and Routes and broaden your skills in Odoo website customization.


Additional Resources and References

  • Odoo Documentation:
    For comprehensive details on Odoo development, visit the Odoo Documentation.
  • GitHub Commit History:
    Review the implementation details and commit history for this custom webpage support module at GitHub Commit.
  • Community Forums:
    Engage with the Odoo community on forums and discussion groups to share ideas and seek help when needed.
  • Tutorial Videos:
    Consider watching related tutorial videos on YouTube that provide visual guides on using Odoo Controllers and Routes.

Final Thoughts

This comprehensive guide has equipped you with the knowledge to add website support to custom webpages using Odoo Controllers and Routes. You learned how to build a simple yet powerful QWeb template, create a matching controller, and integrate dynamic content seamlessly into your website’s layout. By following the active, step-by-step instructions and incorporating effective troubleshooting and best practices, you now have a solid foundation for any Odoo website customization project.

Continue to experiment with your module and extend its functionality. As you gain more experience, you will discover even more ways to leverage the flexibility of Odoo Controllers and Routes in your own projects. Keep coding actively, testing frequently, and remain curious about new techniques that can further enhance your development process.

Happy developing, and may your journey in Odoo website customization be both productive and inspiring!


By applying the strategies and code examples provided in this tutorial, you can advance your skills with Odoo Controllers and Routes. Enjoy exploring the endless possibilities of Odoo development and remember that building dynamic, robust websites is just the beginning of what you can achieve with Odoo 16.


Discover more from teguhteja.id

Subscribe to get the latest posts sent to your email.

Leave a Reply

WP Twitter Auto Publish Powered By : XYZScripts.com