Skip to Content
Меню
Вам необхідно зареєструватися, щоб взаємодіяти зі спільнотою.
Це запитання позначене
2 Відповіді
277 Переглядів

Hello everyone,

I'm learning Odoo development and I've run into a very strange issue that I haven't been able to solve, even after a clean reinstall of the system. I would greatly appreciate your help and expertise.

Environment:

  • Odoo Version: 19 Community
  • Setup: Official Windows Installer
  • Context: Local development environment on C:\Odoo19 (to avoid permission issues).

Objective: To make the product search on the shop (/shop) more precise by searching only for whole words.

The Problem in Action:

When I search for the term "ram", Odoo's default broad search finds the substring "ram" anywhere. This returns incorrect results like "Heramienta" (Spanish for "tool") and "Programa" (Spanish for "program").

The Log Evidence:

The strangest part is that, at the same time, the server log (odoo.log) proves that my custom controller is executing and that my Python filtering logic is perfect. The list of products my code generates is correct, containing only RAM products.

Summary of the Problem:

In short: the code executes correctly, it filters the product list perfectly (confirmed by the log), but the final webpage ignores this correct list and displays the incorrect one. Even using "request.render()" to force a re-render of the template, the visual result does not change.

My Code "(controllers/ main.py)":


# -*- coding: utf-8 -*-

import logging

import re

from odoo import http

from odoo.http import request

from odoo.addons.website_sale.controllers.main import WebsiteSale


_logger = logging.getLogger(__name__)


class CustomWebsiteSearch(WebsiteSale):


    @http.route([

        '/shop',

        '/shop/page/<int:page>',

        '/shop/category/<model("product.public.category"):category>',

        '/shop/category/<model("product.public.category"):category>/page/<int:page>',

    ], type='http', auth="public", website=True, sitemap=WebsiteSale.sitemap_shop)

    def shop(self, page=0, category=None, search='', min_price=0.0, max_price=0.0, ppg=False, **post):

        response = super(CustomWebsiteSearch, self).shop(

            page=page, category=category, search=search, min_price=min_price,

            max_price=max_price, ppg=ppg, **post

        )


        if not search or not response.qcontext.get('products'):

            return response


        _logger.info("--- 1. Netdata Controller INITIALIZED for: '%s' ---", search)


        all_products = response.qcontext['products']

        term = search.lower()

        relevant_products = []


        for product in all_products:

            pattern = r'\b' + re.escape(term) + r'\b'

            if re.search(pattern, product.name.lower()):

                relevant_products.append(product)


        _logger.info("--- 2. Products AFTER filter: %s ---", [p.name for p in relevant_products])

       

        qcontext = response.qcontext

        qcontext['products'] = http.request.env['product.template'].browse([p.id for p in relevant_products])

        qcontext['search_count'] = len(relevant_products)


        return request.render('website_sale.products', qcontext)


What could cause Odoo to ignore the "return request.render(...)" and fail to display the updated data from "qcontext", even when the logs prove the logic is correct and executing? Is this a known issue in Odoo 19 Community? Could it be a conflict with the theme or a cache that isn't being cleared properly?

Аватар
Відмінити
Найкраща відповідь

Hi,


In Odoo 19, your issue happens because the /shop page uses AJAX and OWL rendering, which reloads product results after your controller runs. Even though your Python filtering works, the frontend replaces your filtered list with the default one.


The proper fix is to override Odoo’s search domain before products are loaded instead of re-rendering the template. By customizing the _get_search_domain() method, you can apply whole-word filtering that works with Odoo’s frontend logic.


Try the following code.


# -*- coding: utf-8 -*-

import re

import logging

from odoo import http

from odoo.http import request

from odoo.addons.website_sale.controllers.main import WebsiteSale


_logger = logging.getLogger(__name__)


class CustomWebsiteSearch(WebsiteSale):


    def _get_search_domain(self, search, category, attrib_values, search_in_description=True):

        domain = super()._get_search_domain(search, category, attrib_values, search_in_description)

        if search:

            pattern = r'\b' + re.escape(search.lower()) + r'\b'

            products = request.env['product.template'].sudo().search([])

            filtered_ids = [p.id for p in products if re.search(pattern, p.name.lower())]

            domain = [('id', 'in', filtered_ids)] if filtered_ids else [('id', '=', 0)]

            _logger.info("Whole-word search applied for '%s' -> %s", search, filtered_ids)

        return domain



* Add this controller to your custom module.

* Restart Odoo and upgrade the module.

* Search in /shop — now only exact word matches (e.g., “ram”) will appear.



Hope it helps



Аватар
Відмінити
Найкраща відповідь

There is more to the /shop/... routes than is covered by your source - see also https://github.com/odoo/odoo/blob/19.0/addons/website_sale/controllers/main.py#L487.

What's most crucial to your scenario is the bins key.

A working source - but far from being optimized nor covering all aspects such as filters etc. - is:

# -*- coding: utf-8 -*-

import logging
import re
from odoo.tools import lazy
from odoo import http
from odoo.http import request
from odoo.addons.website_sale.controllers.main import WebsiteSale, TableCompute

_logger = logging.getLogger(__name__)


class CustomWebsiteSearch(WebsiteSale):
    @http.route([
        '/shop',
        '/shop/page/<int:page>',
        '/shop/category/<model("product.public.category"):category>',
        '/shop/category/<model("product.public.category"):category>/page/<int:page>',
    ], type='http', auth="public", website=True, sitemap=WebsiteSale.sitemap_shop)
    def shop(self, page=0, category=None, search='', min_price=0.0, max_price=0.0, ppg=False, **post):
        response = super(CustomWebsiteSearch, self).shop(
            page=page, category=category, search=search, min_price=min_price,
            max_price=max_price, ppg=ppg, **post
        )

        website = request.env['website'].get_current_website()
        ppr = website.shop_ppr or 4

        if not search or not response.qcontext.get('products'):
            return response

        _logger.info("--- 1. Netdata Controller INITIALIZED for: '%s' ---", search)
        all_products = response.qcontext['products']
        term = search.lower()
        relevant_products = []
        for product in all_products:
            pattern = r'\b' + re.escape(term) + r'\b'
            if re.search(pattern, product.name.lower()):
                relevant_products.append(product)

        _logger.info("--- 2. Products AFTER filter: %s ---", [p.name for p in relevant_products])
        qcontext = response.qcontext
        qcontext['products'] = http.request.env['product.template'].browse([p.id for p in relevant_products])
        qcontext['search_product'] = http.request.env['product.template'].browse([p.id for p in relevant_products])
        qcontext['bins'] = lazy(lambda: TableCompute().process(relevant_products, ppg, ppr))
        qcontext['search_count'] = len(relevant_products)
        return request.render('website_sale.products', qcontext)
Аватар
Відмінити
Related Posts Відповіді Переглядів Дія
3
вер. 25
697
1
вер. 25
2059
1
серп. 25
506
0
лип. 25
1278
1
трав. 25
2009