From: Michael Fladischer <FladischerMichael@fladi.at>
Date: Thu, 11 Apr 2024 13:58:36 +0000
Subject: Use local objects.inv in default intersphinx configuration if files
 are present.

---
 sphinxcontrib_django/roles.py | 39 +++++++++++++++++++++++++++++++--------
 1 file changed, 31 insertions(+), 8 deletions(-)

diff --git a/sphinxcontrib_django/roles.py b/sphinxcontrib_django/roles.py
index 7a80d66..24a342f 100644
--- a/sphinxcontrib_django/roles.py
+++ b/sphinxcontrib_django/roles.py
@@ -23,7 +23,10 @@ This module can also be used separately in ``conf.py``::
 """
 from __future__ import annotations
 
+import django
+import os
 import logging
+import sys
 
 from sphinx.application import Sphinx
 from sphinx.config import Config
@@ -78,14 +81,34 @@ def add_default_intersphinx_mappings(app: Sphinx, config: Config) -> None:
     :param app: The Sphinx application object
     :param config: The Sphinx configuration
     """
-    DEFAULT_INTERSPHINX_MAPPING = {
-        "python": ("https://docs.python.org/", None),
-        "sphinx": ("https://www.sphinx-doc.org/en/master/", None),
-        "django": (
-            "https://docs.djangoproject.com/en/stable/",
-            "https://docs.djangoproject.com/en/stable/_objects/",
-        ),
-    }
+    def check_object_path(key, url, path):
+        if os.path.isfile(path):
+            return {key: (url, path)}
+        return {}
+
     if not config.intersphinx_mapping:
+        DEFAULT_INTERSPHINX_MAPPING = {}
+        DEFAULT_INTERSPHINX_MAPPING.update(
+            check_object_path(
+                'python',
+                f"https://docs.python.org/{sys.version_info.major}.{sys.version_info.minor}/",
+                f"/usr/share/doc/python{sys.version_info.major}.{sys.version_info.minor}/html/objects.inv"
+            )
+        )
+        DEFAULT_INTERSPHINX_MAPPING.update(
+            check_object_path(
+                'sphinx',
+                'https://www.sphinx-doc.org/en/master/',
+                '/usr/share/doc/sphinx-doc/html/objects.inv'
+            )
+        )
+        DEFAULT_INTERSPHINX_MAPPING.update(
+            check_object_path(
+                'django',
+                'https://docs.djangoproject.com/en/' + '.'.join((str(c) for c in django.VERSION[:2])) + '/_objects/',
+                '/usr/share/doc/python-django-doc/html/objects.inv'
+            )
+        )
+
         # TYPING: type hints are missing `.intersphinx_mapping` attribute.
         config.intersphinx_mapping = DEFAULT_INTERSPHINX_MAPPING  # type: ignore[attr-defined ]
