How to Override a Controller of a Specific Module in Odoo

Overview

Overriding a controller in Odoo allows you to customise the way HTTP requests are handled by extending or altering the functionality of existing controllers. This can be useful for modifying the behavior of web pages, handling form submissions differently, or integrating new features into your Odoo application.

Overriding a Controller in Odoo

Here’s a basic guide on how to override a controller in Odoo:

To override an existing controller of a specific module core or another module, you can inherit the original controller class and then override the specific method. Make sure to call super() with the class of the original controller.

Example Code Snippet:

Here's an example code snippet demonstrating how to override the "shop_payment_transaction" controller from the "website_sale_stock" module:

This is done by making a super() call to the class of the module whose controller we are overriding, which is WebStockPaymentPortal.

from odoo import http, _
from odoo.http import request
from odoo.exceptions import ValidationError
from odoo.addons.website_sale_stock.controllers.main import PaymentPortal as WebStockPaymentPortal


class PaymentPortal(WebStockPaymentPortal):

@http.route()
       def shop_payment_transaction(self, *args, **kwargs):
       """ Payment transaction override to double check cart quantities before placing the order """
       order = request.website.sale_get_order()
       values = []
       for line in order.order_line:
           if line.product_id.type == 'product' and not line.product_id.allow_out_of_stock_order:
           cart_qty = sum(order.order_line.filtered(lambda p: p.product_id.id == line.product_id.id).mapped('product_uom_qty'))
           website = request.env['website'].get_current_website()
           website_location_id = website.location_id or False
           if website_location_id:
              avl_qty =
line.product_id.with_context(location=website_location_id.id).free_qty

          else:
              avl_qty = line.product_id.with_context(warehouse=order.warehouse_id.id).free_qty
          if cart_qty > avl_qty:
             values.append(_(
                  'You ask for %(quantity)s products but only %(available_qty)s is available',
                          quantity=cart_qty,
                          available_qty=avl_qty if avl_qty > 0 else 0
                  ))
          if values:
                  raise ValidationError('. '.join(values) + '.')
          return super(WebStockPaymentPortal, self).shop_payment_transaction(*args, **kwargs)

By utilising Odoo's controller override capabilities, you can customise HTTP request handling to suit your specific needs, enhancing the functionality and customisation of your Odoo application.

Fix Memory Limit Error in Odoo Module Installation