From dabaa9aea5d42a749b2c5e8a28f4a2af0e8c5a9f Mon Sep 17 00:00:00 2001 From: Oliver Date: Mon, 1 Nov 2021 23:40:21 +1100 Subject: [PATCH] Adds a function to construct an "absolute" URL Useful for providing an external link (e.g. in an email) --- InvenTree/InvenTree/helpers.py | 27 +++++++++++++++++++++++++ InvenTree/report/templatetags/report.py | 14 ++++--------- 2 files changed, 31 insertions(+), 10 deletions(-) diff --git a/InvenTree/InvenTree/helpers.py b/InvenTree/InvenTree/helpers.py index 319b88cb09..4b0f31a702 100644 --- a/InvenTree/InvenTree/helpers.py +++ b/InvenTree/InvenTree/helpers.py @@ -69,6 +69,33 @@ def getStaticUrl(filename): return os.path.join(STATIC_URL, str(filename)) +def construct_absolute_url(url): + """ + Construct (or attempt to construct) an absolute URL from a relative URL. + + This is useful when (for example) sending an email to a user with a link + to something in the InvenTree web framework. + + This requires the BASE_URL configuration option to be set! + """ + + base = str(InvenTreeSetting.get_setting('INVENTREE_BASE_URL')) + + url = str(url) + + if not base: + return url + + # Strip trailing slash from base url + if base.endswith('/'): + base = base[:-1] + + if url.startswith('/'): + url = url[1:] + + url = f"{base}/{url}" + + def getBlankImage(): """ Return the qualified path for the 'blank image' placeholder. diff --git a/InvenTree/report/templatetags/report.py b/InvenTree/report/templatetags/report.py index 45d11c1d2d..9593db1885 100644 --- a/InvenTree/report/templatetags/report.py +++ b/InvenTree/report/templatetags/report.py @@ -14,6 +14,8 @@ from stock.models import StockItem from common.models import InvenTreeSetting +import InvenTree.helpers + register = template.Library() @@ -119,18 +121,10 @@ def internal_link(link, text): text = str(text) - base_url = InvenTreeSetting.get_setting('INVENTREE_BASE_URL') + url = InvenTree.helpers.construct_absolute_url(link) # If the base URL is not set, just return the text - if not base_url: + if not url: return text - if not base_url.endswith('/'): - base_url += '/' - - if base_url.endswith('/') and link.startswith('/'): - link = link[1:] - - url = f"{base_url}{link}" - return mark_safe(f'{text}')