Перейти к содержимому
Odoo Меню
  • Войти
  • Попробовать бесплатно
  • Модули
    Финансы
    • Бухгалтерия
    • Выставление счетов
    • Расходы
    • Таблицы
    • Документооборот
    • Подпись
    Продажи
    • CRM
    • Продажи
    • POS Магазин
    • POS Ресторан
    • Подписки
    • Аренда
    Вебсайты
    • Конструктор вебсайтов
    • eCommerce
    • Блог
    • Форум
    • Онлайн-чат
    • Электронное обучение
    Логистика
    • Склад
    • Производство
    • PLM
    • Закупки
    • Обслуживание
    • Качество
    Отдел кадров
    • Сотрудники
    • Подбор персонала
    • Отпуска
    • Оценка персонала
    • Реферальная программа
    • Автопарк
    Маркетинг
    • SMM
    • E-mail рассылки
    • СМС рассылки
    • Мероприятия
    • Автоматизация маркетинга
    • Опросы
    Услуги
    • Проекты
    • Табели
    • Выездной сервис
    • Поддержка
    • Планирование
    • Встречи
    Продуктивность
    • Обсуждения
    • Согласование
    • IoT
    • VoIP-телефония
    • Knowledge
    • WhatsApp
    Сторонние приложения Модуль Студия Odoo Платформа Odoo Cloud
  • Индустрии
    Розничная торговля
    • Книжный магазин
    • Магазин одежды
    • Мебельный магазин
    • Продуктовый магазин
    • Строительный магазин
    • Магазин игрушек
    Гостинично-ресторанный бизнес
    • Бар и паб
    • Ресторан
    • Фастфуд
    • Гостевой дом
    • Дистрибьютор напитков
    • Отель
    Недвижимость
    • Агентство недвижимости
    • Архитектурное бюро
    • Строительство
    • Управление недвижимостью
    • Ландшафтный дизайн
    • Товарищество собственников жилья
    Консалтинг
    • Бухгалтерская фирма
    • Партнер Odoo
    • Маркетинговое агентство
    • Юридическая фирма
    • Подбор персонала
    • Аудиторское бюро
    Производство
    • Текстиль
    • Металл
    • Мебель
    • Продукты питания
    • Пивоварня
    • Корпоративные сувениры
    Здоровье и фитнес
    • Спортивный комплекс
    • Магазин оптики
    • Фитнес-клуб
    • Велнес-центр
    • Аптека
    • Салон красоты
    Услуги
    • Специалист по бытовым услугам
    • Продажа и обслуживание IT-оборудования
    • Солнечные энергосистемы
    • Производство обуви
    • Клининг
    • Системы ОВКВ
    Прочее
    • Некоммерческая организация
    • Консалтинг в сфере устойчивого развития
    • Аренда рекламных щитов
    • Бизнес по фотосъемке
    • Прокат велосипедов
    • Реселлер программного обеспечения
    Все индустрии
  • Community
    Обучение
    • Видео уроки
    • Документация
    • Сертификация
    • Тренинг
    • Блог
    • Подкаст
    Образование и развитие
    • Образовательная программа
    • Деловая игра Scale Up!
    • Экскурсия в офис Odoo
    ПО
    • Скачать
    • Сравнить версии
    • Релизы
    Сотрудничество
    • Github
    • Форум
    • Мероприятия
    • Перевод
    • Стать партнером
    • Услуги для партнеров
    • Зарегистрировать бухгалтерскую фирму
    Услуги
    • Найти партнера
    • Найти бухгалтера
    • Встреча с экспертом
    • Услуги по внедрению
    • Отзывы клиентов
    • Поддержка
    • Обновления
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Заказать демонстрацию
  • Цены
  • Поддержка

Odoo is the world's easiest all-in-one management software.
It includes hundreds of business apps:

  • CRM
  • e-Commerce
  • Бухгалтерия
  • Склад
  • PoS
  • Проекты
  • MRP
All apps
Чтобы взаимодействовать с сообществом, необходимо зарегистрироваться.
Все посты Люди Значки
Теги (Смотреть все)
odoo accounting v14 pos v15
Об этом форуме
Чтобы взаимодействовать с сообществом, необходимо зарегистрироваться.
Все посты Люди Значки
Теги (Смотреть все)
odoo accounting v14 pos v15
Об этом форуме
Помощь

Controller

Подписаться

Получайте уведомления о появлении активности в этом посте

Этот вопрос был отмечен
urlcontrollersredirection
2985 Представления
Аватар
Ravi Bhatt

***model.py***

from odoo import api, fields, modelsfrom odoo.exceptions import ValidationErrorimport re

class UrlRedirect(models.Model): _name = 'url.redirect' _description = "Url redirect"

name = fields.Char(string='Name', required=True) 
source_url = fields.Char(string='Identifier', index=True) 
destination_url = fields.Char(string="URL to redirect")  
active = fields.Boolean(default=True)
visit_count = fields.Integer(string='Visit Count', default=0) 
visitor_id = fields.Many2one('res.users', string='Partner')
source_url_with_prefix = fields.Char(string='Identifier with Prefix', compute="_compute_source_url_with_prefix")

@api.depends('source_url') def _compute_source_url_with_prefix(self): for record in self: if record.source_url and not record.source_url.startswith('r-'): record.source_url_with_prefix = 'r-' + record.source_url else: record.source_url_with_prefix = record.source_url


@api.constrains('source_url') def _check_source_url(self): for record in self: if not re.match(r'^[a-zA-Z0-9\-]+$', record.source_url): raise ValidationError("The source URL can only contain a-z, A-Z, 0-9, and hyphens.")


***controller.py***
from odoo import http

from odoo.http import request

import re


def is_valid_url(source_url):

        import re

        return re.match(r'^[a-zA-Z0-9\-]+$', source_url)


class URLRedirectController(http.Controller):


    @http.route('/', type='http', auth='public', website=True)

    def url_redirect(self, source_url):

        if not is_valid_url(source_url):

            return "Invalid URL. Only letters, digits, and hyphens are allowed."


        try:

            redirect_record = request.env['url.redirect'].search([('source_url', '=', source_url)], limit=1)

            if redirect_record:

                redirect_record.visit_count += 1

                destination_url = redirect_record.destination_url

                return request.redirect(destination_url, local=False)

            else:

                return request.not_found()

        except Exception as e:

            return str(e)

            

        else:

            return request.not_found()


the thing i want to do is when i enter the source URL in search bar i should be redirected to the destination URL that is working properly but i also want to count the number of visits on that specific URL which i took it as a string but when i try to enter the URL and successfully redirected to destination URL visitor counter increases by 2 instead of 1 this is probably happening because of the destination URL is also type of string so to avoid this thing i tried to added prefix r- before / so i replaced first line like  this """@http.route('/r-', type='http', auth='public', website=True)""" but now i have to manually enter the r-prefix whenever i try to enter source URL and fullfill the purpose i previously did, is there anyway by which i can always get prefix r- in the url even if i just enter some string (for example """/shop""" should be automatically converted into """/r-shop""") and also i should be redirected to the destination location. ***model.py***

from odoo import api, fields, modelsfrom odoo.exceptions import ValidationErrorimport re

class UrlRedirect(models.Model): _name = 'url.redirect' _description = "Url redirect"

name = fields.Char(string='Name', required=True) website_id = fields.Many2one('website', string="Website", ondelete='cascade', index=True) source_url = fields.Char(string='Identifier', index=True) destination_url = fields.Char(string="URL to redirect") # route_id = fields.Many2one('website.route') active = fields.Boolean(default=True) visit_count = fields.Integer(string='Visit Count', default=0) visitor_id = fields.Many2one('res.users', string='Partner') source_url_with_prefix = fields.Char(string='Identifier with Prefix', compute="_compute_source_url_with_prefix")

@api.depends('source_url') def _compute_source_url_with_prefix(self): for record in self: if record.source_url and not record.source_url.startswith('r-'): record.source_url_with_prefix = 'r-' + record.source_url else: record.source_url_with_prefix = record.source_url


@api.constrains('source_url') def _check_source_url(self): for record in self: if not re.match(r'^[a-zA-Z0-9\-]+$', record.source_url): raise ValidationError("The source URL can only contain a-z, A-Z, 0-9, and hyphens.")


***controller.py***
from odoo import http

from odoo.http import request

import re


def is_valid_url(source_url):

        import re

        return re.match(r'^[a-zA-Z0-9\-]+$', source_url)


class URLRedirectController(http.Controller):


    @http.route('/', type='http', auth='public', website=True)

    def url_redirect(self, source_url):

        if not is_valid_url(source_url):

            return "Invalid URL. Only letters, digits, and hyphens are allowed."


        try:

            redirect_record = request.env['url.redirect'].search([('source_url', '=', source_url)], limit=1)

            if redirect_record:

                redirect_record.visit_count += 1

                destination_url = redirect_record.destination_url

                return request.redirect(destination_url, local=False)

            else:

                return request.not_found()

        except Exception as e:

            return str(e)

            

        else:

            return request.not_found()


the thing i want to do is when i enter the source URL in search bar i should be redirected to the destination URL that is working properly but i also want to count the number of visits on that specific URL which i took it as a string but when i try to enter the URL and successfully redirected to destination URL visitor counter increases by 2 instead of 1 this is probably happening because of the destination URL is also type of string so to avoid this thing i tried to added prefix r- before / so i replaced first line like  this """@http.route('/r-', type='http', auth='public', website=True)""" but now i have to manually enter the r-prefix whenever i try to enter source URL and fullfill the purpose i previously did, is there anyway by which i can always get prefix r- in the url even if i just enter some string (for example """/shop""" should be automatically converted into """/r-shop""") and also i should be redirected to the destination location. 

0
Аватар
Отменить
Не оставайтесь в стороне – присоединяйтесь к обсуждению!

Создайте аккаунт сегодня, чтобы получить доступ к эксклюзивным функциям и стать частью нашего замечательного сообщества!

Регистрация
Похожие посты Ответы Просмотры Активность
change website product page URL
url redirection
Аватар
0
февр. 21
3812
i want to access of querystring in controller Решено
url controllers odoo10
Аватар
Аватар
Аватар
3
июл. 19
16570
Odoo V10: Disable '?debug' in the url
debug url controllers
Аватар
0
мар. 18
365
Open an url using python, without using return
models actions url controllers
Аватар
Аватар
1
июл. 21
5972
i want to access model objects in odoo controlle Решено
query url controllers odoo10
Аватар
Аватар
2
янв. 20
8348
Сообщество
  • Видео уроки
  • Документация
  • Форум
Открытый исходный код
  • Скачать
  • Github
  • Runbot
  • Перевод
Услуги
  • Хостинг Odoo.sh
  • Поддержка
  • Обновление
  • Индивидуальные решения по доработке
  • Образование
  • Найти бухгалтера
  • Найти партнера
  • Стать партнером
О нас
  • Наша компания
  • Активы бренда
  • Cвяжитесь с нами
  • Вакансии
  • Мероприятия
  • Подкаст
  • Блог
  • Клиенты
  • Правовые документы • Конфиденциальность
  • Безопасность
الْعَرَبيّة Català 简体中文 繁體中文 (台灣) Čeština Dansk Nederlands English Suomi Français Deutsch हिंदी Bahasa Indonesia Italiano 日本語 한국어 (KR) Lietuvių kalba Język polski Português (BR) română русский язык Slovenský jazyk slovenščina Español (América Latina) Español ภาษาไทย Türkçe українська Tiếng Việt

Odoo – это набор бизнес-модулей с открытым исходным кодом, который закроет все потребности вашей компании: CRM, E-commerce, Бухгалтерия, Склад, POS, управление проектами и др.

Odoo сочетает в себе простоту использования и полную интеграцию всех бизнес-процессов в одной системе.

Website made with

Odoo Experience on YouTube

1. Use the live chat to ask your questions.
2. The operator answers within a few minutes.

Live support on Youtube
Watch now