Overslaan naar inhoud
Odoo Menu
  • Aanmelden
  • Probeer het gratis
  • Apps
    Financiën
    • Boekhouding
    • Facturatie
    • Onkosten
    • Spreadsheet (BI)
    • Documenten
    • Ondertekenen
    Verkoop
    • CRM
    • Verkoop
    • Kassasysteem winkel
    • Kassasysteem Restaurant
    • Abonnementen
    • Verhuur
    Websites
    • Websitebouwer
    • E-commerce
    • Blog
    • Forum
    • Live Chat
    • eLearning
    Bevoorradingsketen
    • Voorraad
    • Productie
    • PLM
    • Inkoop
    • Onderhoud
    • Kwaliteit
    Personeelsbeheer
    • Werknemers
    • Werving & Selectie
    • Verlof
    • Evaluaties
    • Aanbevelingen
    • Wagenpark
    Marketing
    • Social media Marketing
    • E-mailmarketing
    • SMS Marketing
    • Evenementen
    • Marketingautomatisering
    • Enquêtes
    Diensten
    • Project
    • Urenstaten
    • Buitendienst
    • Helpdesk
    • Planning
    • Afspraken
    Productiviteit
    • Chat
    • Goedkeuringen
    • IoT
    • VoIP
    • Kennis
    • WhatsApp
    Apps van derden Odoo Studio Odoo Cloud Platform
  • Bedrijfstakken
    Detailhandel
    • Boekhandel
    • kledingwinkel
    • Meubelzaak
    • Supermarkt
    • Bouwmarkt
    • Speelgoedwinkel
    Food & Hospitality
    • Bar en Pub
    • Restaurant
    • Fastfood
    • Gastenverblijf
    • Drankenhandelaar
    • Hotel
    Vastgoed
    • Makelaarskantoor
    • Architectenbureau
    • Bouw
    • Vastgoedbeheer
    • Tuinieren
    • Vereniging van eigenaren
    Consulting
    • Accountantskantoor
    • Odoo Partner
    • Marketingbureau
    • Advocatenkantoor
    • Talentenwerving
    • Audit & Certificering
    Productie
    • Textiel
    • Metaal
    • Meubels
    • Eten
    • Brewery
    • Relatiegeschenken
    Gezondheid & Fitness
    • Sportclub
    • Opticien
    • Fitnesscentrum
    • Wellness-medewerkers
    • Apotheek
    • Kapper
    Trades
    • Klusjesman
    • IT-hardware & support
    • Zonne-energiesystemen
    • Schoenmaker
    • Schoonmaakdiensten
    • HVAC-diensten
    Andere
    • Non-profitorganisatie
    • Milieuagentschap
    • Verhuur van Billboards
    • Fotograaf
    • Fietsleasing
    • Softwareverkoper
    Browse all Industries
  • Community
    Leren
    • Tutorials
    • Documentatie
    • Certificeringen
    • Training
    • Blog
    • Podcast
    Versterk het onderwijs
    • Onderwijs- programma
    • Scale Up! Business Game
    • Bezoek Odoo
    Download de Software
    • Downloaden
    • Vergelijk edities
    • Releases
    Werk samen
    • Github
    • Forum
    • Evenementen
    • Vertalingen
    • Word een Partner
    • Services for Partners
    • Registreer je accountantskantoor
    Diensten
    • Vind een partner
    • Vind een boekhouder
    • Een adviseur ontmoeten
    • Implementatiediensten
    • Klantreferenties
    • Ondersteuning
    • Upgrades
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Vraag een demo aan
  • Prijzen
  • Help

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

  • CRM
  • e-Commerce
  • Boekhouding
  • Voorraad
  • PoS
  • Project
  • MRP
All apps
Je moet geregistreerd zijn om te kunnen communiceren met de community.
Alle posts Personen Badges
Labels (Bekijk alle)
odoo accounting v14 pos v15
Over dit forum
Je moet geregistreerd zijn om te kunnen communiceren met de community.
Alle posts Personen Badges
Labels (Bekijk alle)
odoo accounting v14 pos v15
Over dit forum
Help

Controller

Inschrijven

Ontvang een bericht wanneer er activiteit is op deze post

Deze vraag is gerapporteerd
urlcontrollersredirection
2990 Weergaven
Avatar
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
Avatar
Annuleer
Geniet je van het gesprek? Blijf niet alleen lezen, doe ook mee!

Maak vandaag nog een account aan om te profiteren van exclusieve functies en deel uit te maken van onze geweldige community!

Aanmelden
Gerelateerde posts Antwoorden Weergaven Activiteit
change website product page URL
url redirection
Avatar
0
feb. 21
3812
i want to access of querystring in controller Opgelost
url controllers odoo10
Avatar
Avatar
Avatar
3
jul. 19
16571
Odoo V10: Disable '?debug' in the url
debug url controllers
Avatar
0
mrt. 18
365
Open an url using python, without using return
models actions url controllers
Avatar
Avatar
1
jul. 21
5973
i want to access model objects in odoo controlle Opgelost
query url controllers odoo10
Avatar
Avatar
2
jan. 20
8351
Community
  • Tutorials
  • Documentatie
  • Forum
Open Source
  • Downloaden
  • Github
  • Runbot
  • Vertalingen
Diensten
  • Odoo.sh Hosting
  • Ondersteuning
  • Upgrade
  • Gepersonaliseerde ontwikkelingen
  • Onderwijs
  • Vind een boekhouder
  • Vind een partner
  • Word een Partner
Over ons
  • Ons bedrijf
  • Merkelementen
  • Neem contact met ons op
  • Vacatures
  • Evenementen
  • Podcast
  • Blog
  • Klanten
  • Juridisch • Privacy
  • Beveiliging
الْعَرَبيّة 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 is een suite van open source zakelijke apps die aan al je bedrijfsbehoeften voldoet: CRM, E-commerce, boekhouding, inventaris, kassasysteem, projectbeheer, enz.

Odoo's unieke waardepropositie is om tegelijkertijd zeer gebruiksvriendelijk en volledig geïntegreerd te zijn.

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