From 3f6904720a1cec6192d86914d3ceebe332559d6f Mon Sep 17 00:00:00 2001 From: Kai Schlamp Date: Thu, 23 May 2024 13:55:53 +0000 Subject: [PATCH] Fix base_url template tag --- .../common/templatetags/common_extras.py | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/adit_radis_shared/common/templatetags/common_extras.py b/adit_radis_shared/common/templatetags/common_extras.py index 671ecbc..27d9fee 100644 --- a/adit_radis_shared/common/templatetags/common_extras.py +++ b/adit_radis_shared/common/templatetags/common_extras.py @@ -2,6 +2,8 @@ from datetime import date, datetime, time from typing import Any +from django.conf import settings +from django.contrib.sites.models import Site from django.contrib.sites.shortcuts import get_current_site from django.http import HttpRequest from django.template import Library @@ -19,10 +21,17 @@ def access_item(d: dict, key: str) -> Any: @register.simple_tag(takes_context=True) def base_url(context: dict[str, Any]) -> str: - # Requires django.template.context_processors.request - request: HttpRequest = context["request"] - domain = get_current_site(request).domain - protocol = "https" if request.is_secure() else "http" + # To have request in context, django.template.context_processors.request + # is required in the context_processors settings. + request: HttpRequest | None = context.get("request") + + if request is not None: + domain = get_current_site(request).domain + protocol = "https" if request.is_secure() else "http" + else: + domain = Site.objects.get_current() + protocol = "https" if not settings.DEBUG else "http" + return f"{protocol}://{domain}"