django-docs-viewer 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Malte Gerth
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,198 @@
1
+ Metadata-Version: 2.4
2
+ Name: django-docs-viewer
3
+ Version: 0.1.0
4
+ Summary: A simple in-app Markdown documentation viewer for Django.
5
+ License-Expression: MIT
6
+ License-File: LICENSE
7
+ Keywords: django,documentation,markdown,docs
8
+ Author: Malte Gerth
9
+ Author-email: mail@malte-gerth.de
10
+ Requires-Python: >=3.10
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Environment :: Web Environment
13
+ Classifier: Framework :: Django
14
+ Classifier: Framework :: Django :: 4
15
+ Classifier: Framework :: Django :: 4.2
16
+ Classifier: Framework :: Django :: 5
17
+ Classifier: Framework :: Django :: 5.0
18
+ Classifier: Framework :: Django :: 5.1
19
+ Classifier: Framework :: Django :: 5.2
20
+ Classifier: Framework :: Django :: 6.0
21
+ Classifier: Intended Audience :: Developers
22
+ Classifier: Programming Language :: Python
23
+ Classifier: Programming Language :: Python :: 3.10
24
+ Classifier: Programming Language :: Python :: 3.11
25
+ Classifier: Programming Language :: Python :: 3.12
26
+ Classifier: Programming Language :: Python :: 3.13
27
+ Classifier: Programming Language :: Python :: 3.14
28
+ Classifier: Topic :: Documentation
29
+ Classifier: Topic :: Software Development :: Libraries
30
+ Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
31
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
32
+ Requires-Dist: django (>=4.2)
33
+ Requires-Dist: markdown (>=3.4)
34
+ Project-URL: Documentation, https://github.com/JanMalte/django-docs-viewer
35
+ Project-URL: Homepage, https://github.com/JanMalte/django-docs-viewer
36
+ Project-URL: Repository, https://github.com/JanMalte/django-docs-viewer
37
+ Description-Content-Type: text/markdown
38
+
39
+ # django-docs-viewer
40
+
41
+ [![tests](https://github.com/JanMalte/django-docs-viewer/actions/workflows/run-tests.yml/badge.svg)](https://github.com/JanMalte/django-docs-viewer/actions/workflows/run-tests.yml)
42
+ [![PyPI version](https://img.shields.io/pypi/v/django-docs-viewer.svg)](https://pypi.org/project/django-docs-viewer/)
43
+ [![Supported Python versions](https://img.shields.io/pypi/pyversions/django-docs-viewer.svg)](https://pypi.org/project/django-docs-viewer/)
44
+ [![Supported Django versions](https://img.shields.io/badge/django-4.2%20%7C%205.0%20%7C%205.1%20%7C%205.2%20%7C%206.0-blue.svg)](https://www.djangoproject.com/)
45
+ [![License: MIT](https://img.shields.io/github/license/JanMalte/django-docs-viewer.svg)](https://github.com/JanMalte/django-docs-viewer/blob/main/LICENSE)
46
+
47
+ A simple in-app Markdown documentation viewer for Django.
48
+
49
+ Point it at a directory of Markdown files and it serves them as browsable
50
+ documentation pages with an auto-generated sidebar. No build step, no database,
51
+ no models — pages are read from disk and rendered on request.
52
+
53
+ ## Features
54
+
55
+ - Renders Markdown files (`fenced_code`, `tables`, `toc`, `sane_lists`).
56
+ - Auto-generated sidebar navigation, grouped by folder.
57
+ - Automatic per-page table of contents built from each page's headings.
58
+ - Case-insensitive, traversal-safe URL resolution.
59
+ - Serves images referenced from your Markdown.
60
+ - Login required by default; can be made public with one setting.
61
+ - Self-contained, overridable templates.
62
+
63
+ ## How it compares
64
+
65
+ The niche is *zero-build, database-free, self-navigating docs*: Markdown
66
+ rendered at request time, with the sidebar and per-page table of contents built
67
+ from the folder tree and headings.
68
+ [django-markdown-view](https://github.com/rgs258/django-markdown-view) also
69
+ renders at request time but builds no navigation;
70
+ [Django Spellbook](https://django-spellbook.org/) builds navigation but via a
71
+ generation step and as part of a larger Markdown-components framework.
72
+
73
+ ## Installation
74
+
75
+ ```
76
+ pip install django-docs-viewer
77
+ ```
78
+
79
+ ## Usage
80
+
81
+ Add the app to `INSTALLED_APPS` and point `DOCS_VIEWER_ROOT` at your docs
82
+ directory:
83
+
84
+ ```python
85
+ # settings.py
86
+ INSTALLED_APPS = [
87
+ # ...
88
+ "docs_viewer",
89
+ ]
90
+
91
+ DOCS_VIEWER_ROOT = BASE_DIR / "docs"
92
+ ```
93
+
94
+ Include the URLs:
95
+
96
+ ```python
97
+ # urls.py
98
+ from django.urls import include, path
99
+
100
+ urlpatterns = [
101
+ # ...
102
+ path("docs/", include("docs_viewer.urls")),
103
+ ]
104
+ ```
105
+
106
+ By default the docs require an authenticated user and redirect anonymous
107
+ visitors to `LOGIN_URL`, so make sure your project has a login view — or set
108
+ `DOCS_VIEWER_LOGIN_REQUIRED = False` to make the docs public.
109
+
110
+ Your docs directory can be flat:
111
+
112
+ ```
113
+ docs/
114
+ ├── README.md # landing page + site title
115
+ ├── 01-getting-started.md
116
+ └── 02-configuration.md
117
+ ```
118
+
119
+ or nested, with folders becoming sidebar groups:
120
+
121
+ ```
122
+ docs/
123
+ ├── README.md # landing page + site title
124
+ └── manual/
125
+ ├── 01-getting-started.md
126
+ ├── 02-configuration.md
127
+ └── images/
128
+ └── status-legend.png
129
+ ```
130
+
131
+ ## Settings
132
+
133
+ | Setting | Default | Description |
134
+ | ---------------------------- | ------------------------- | -------------------------------------------------------- |
135
+ | `DOCS_VIEWER_ROOT` | *(required)* | Path to the directory containing your Markdown files. |
136
+ | `DOCS_VIEWER_BASE_TEMPLATE` | `"docs_viewer/base.html"` | Template the docs page extends. Point at your own layout. |
137
+ | `DOCS_VIEWER_LOGIN_REQUIRED` | `True` | Redirect anonymous users to `LOGIN_URL`. Set `False` to make docs public. |
138
+ | `DOCS_VIEWER_TITLE` | `"Documentation"` | Fallback page title when no index heading is available. |
139
+ | `DOCS_VIEWER_TOC_DEPTH` | `"2-3"` | Heading levels included in the per-page table of contents. |
140
+ | `DOCS_VIEWER_SKIP_DIRS` | `["_*"]` | Glob patterns; directories matching any are hidden (excluded from navigation and not served). A custom value replaces the default, so include `"_*"` if you still want underscore-prefixed directories hidden. |
141
+
142
+ The page title is taken from the first level-1 heading of the index
143
+ (`index.md` or `README.md`) at the docs root, falling back to
144
+ `DOCS_VIEWER_TITLE`.
145
+
146
+ ## Customizing the template
147
+
148
+ The docs page (`docs_viewer/detail.html`) extends whatever template
149
+ `DOCS_VIEWER_BASE_TEMPLATE` names, resolved dynamically at render time. By
150
+ default it extends the minimal `docs_viewer/base.html` bundled with the app, so
151
+ it works with no configuration.
152
+
153
+ To make docs pages inherit your site's chrome, point the setting at your own
154
+ base template:
155
+
156
+ ```python
157
+ DOCS_VIEWER_BASE_TEMPLATE = "myproject/base.html"
158
+ ```
159
+
160
+ Your base template only needs a `content` block (and, optionally, a `title`
161
+ block):
162
+
163
+ ```html
164
+ {% block title %}{% endblock %}
165
+ ...
166
+ {% block content %}{% endblock %}
167
+ ```
168
+
169
+ To change the docs page itself rather than the surrounding layout, override
170
+ `docs_viewer/detail.html` in your own template directory.
171
+
172
+ ## Translations
173
+
174
+ The interface strings ship translated into English, German and French. The
175
+ active language follows Django's usual i18n machinery, so enable
176
+ `django.middleware.locale.LocaleMiddleware` (and keep `USE_I18N = True`) if you
177
+ want the docs to follow the request's language.
178
+
179
+ ## Development
180
+
181
+ ```
182
+ poetry install
183
+ poetry run python manage.py test tests
184
+ ```
185
+
186
+ Run the full support matrix with [tox](https://tox.wiki):
187
+
188
+ ```
189
+ poetry run tox
190
+ ```
191
+
192
+ See [CONTRIBUTING.md](CONTRIBUTING.md) for coverage, translations, and the
193
+ pull-request checklist.
194
+
195
+ ## License
196
+
197
+ MIT
198
+
@@ -0,0 +1,159 @@
1
+ # django-docs-viewer
2
+
3
+ [![tests](https://github.com/JanMalte/django-docs-viewer/actions/workflows/run-tests.yml/badge.svg)](https://github.com/JanMalte/django-docs-viewer/actions/workflows/run-tests.yml)
4
+ [![PyPI version](https://img.shields.io/pypi/v/django-docs-viewer.svg)](https://pypi.org/project/django-docs-viewer/)
5
+ [![Supported Python versions](https://img.shields.io/pypi/pyversions/django-docs-viewer.svg)](https://pypi.org/project/django-docs-viewer/)
6
+ [![Supported Django versions](https://img.shields.io/badge/django-4.2%20%7C%205.0%20%7C%205.1%20%7C%205.2%20%7C%206.0-blue.svg)](https://www.djangoproject.com/)
7
+ [![License: MIT](https://img.shields.io/github/license/JanMalte/django-docs-viewer.svg)](https://github.com/JanMalte/django-docs-viewer/blob/main/LICENSE)
8
+
9
+ A simple in-app Markdown documentation viewer for Django.
10
+
11
+ Point it at a directory of Markdown files and it serves them as browsable
12
+ documentation pages with an auto-generated sidebar. No build step, no database,
13
+ no models — pages are read from disk and rendered on request.
14
+
15
+ ## Features
16
+
17
+ - Renders Markdown files (`fenced_code`, `tables`, `toc`, `sane_lists`).
18
+ - Auto-generated sidebar navigation, grouped by folder.
19
+ - Automatic per-page table of contents built from each page's headings.
20
+ - Case-insensitive, traversal-safe URL resolution.
21
+ - Serves images referenced from your Markdown.
22
+ - Login required by default; can be made public with one setting.
23
+ - Self-contained, overridable templates.
24
+
25
+ ## How it compares
26
+
27
+ The niche is *zero-build, database-free, self-navigating docs*: Markdown
28
+ rendered at request time, with the sidebar and per-page table of contents built
29
+ from the folder tree and headings.
30
+ [django-markdown-view](https://github.com/rgs258/django-markdown-view) also
31
+ renders at request time but builds no navigation;
32
+ [Django Spellbook](https://django-spellbook.org/) builds navigation but via a
33
+ generation step and as part of a larger Markdown-components framework.
34
+
35
+ ## Installation
36
+
37
+ ```
38
+ pip install django-docs-viewer
39
+ ```
40
+
41
+ ## Usage
42
+
43
+ Add the app to `INSTALLED_APPS` and point `DOCS_VIEWER_ROOT` at your docs
44
+ directory:
45
+
46
+ ```python
47
+ # settings.py
48
+ INSTALLED_APPS = [
49
+ # ...
50
+ "docs_viewer",
51
+ ]
52
+
53
+ DOCS_VIEWER_ROOT = BASE_DIR / "docs"
54
+ ```
55
+
56
+ Include the URLs:
57
+
58
+ ```python
59
+ # urls.py
60
+ from django.urls import include, path
61
+
62
+ urlpatterns = [
63
+ # ...
64
+ path("docs/", include("docs_viewer.urls")),
65
+ ]
66
+ ```
67
+
68
+ By default the docs require an authenticated user and redirect anonymous
69
+ visitors to `LOGIN_URL`, so make sure your project has a login view — or set
70
+ `DOCS_VIEWER_LOGIN_REQUIRED = False` to make the docs public.
71
+
72
+ Your docs directory can be flat:
73
+
74
+ ```
75
+ docs/
76
+ ├── README.md # landing page + site title
77
+ ├── 01-getting-started.md
78
+ └── 02-configuration.md
79
+ ```
80
+
81
+ or nested, with folders becoming sidebar groups:
82
+
83
+ ```
84
+ docs/
85
+ ├── README.md # landing page + site title
86
+ └── manual/
87
+ ├── 01-getting-started.md
88
+ ├── 02-configuration.md
89
+ └── images/
90
+ └── status-legend.png
91
+ ```
92
+
93
+ ## Settings
94
+
95
+ | Setting | Default | Description |
96
+ | ---------------------------- | ------------------------- | -------------------------------------------------------- |
97
+ | `DOCS_VIEWER_ROOT` | *(required)* | Path to the directory containing your Markdown files. |
98
+ | `DOCS_VIEWER_BASE_TEMPLATE` | `"docs_viewer/base.html"` | Template the docs page extends. Point at your own layout. |
99
+ | `DOCS_VIEWER_LOGIN_REQUIRED` | `True` | Redirect anonymous users to `LOGIN_URL`. Set `False` to make docs public. |
100
+ | `DOCS_VIEWER_TITLE` | `"Documentation"` | Fallback page title when no index heading is available. |
101
+ | `DOCS_VIEWER_TOC_DEPTH` | `"2-3"` | Heading levels included in the per-page table of contents. |
102
+ | `DOCS_VIEWER_SKIP_DIRS` | `["_*"]` | Glob patterns; directories matching any are hidden (excluded from navigation and not served). A custom value replaces the default, so include `"_*"` if you still want underscore-prefixed directories hidden. |
103
+
104
+ The page title is taken from the first level-1 heading of the index
105
+ (`index.md` or `README.md`) at the docs root, falling back to
106
+ `DOCS_VIEWER_TITLE`.
107
+
108
+ ## Customizing the template
109
+
110
+ The docs page (`docs_viewer/detail.html`) extends whatever template
111
+ `DOCS_VIEWER_BASE_TEMPLATE` names, resolved dynamically at render time. By
112
+ default it extends the minimal `docs_viewer/base.html` bundled with the app, so
113
+ it works with no configuration.
114
+
115
+ To make docs pages inherit your site's chrome, point the setting at your own
116
+ base template:
117
+
118
+ ```python
119
+ DOCS_VIEWER_BASE_TEMPLATE = "myproject/base.html"
120
+ ```
121
+
122
+ Your base template only needs a `content` block (and, optionally, a `title`
123
+ block):
124
+
125
+ ```html
126
+ {% block title %}{% endblock %}
127
+ ...
128
+ {% block content %}{% endblock %}
129
+ ```
130
+
131
+ To change the docs page itself rather than the surrounding layout, override
132
+ `docs_viewer/detail.html` in your own template directory.
133
+
134
+ ## Translations
135
+
136
+ The interface strings ship translated into English, German and French. The
137
+ active language follows Django's usual i18n machinery, so enable
138
+ `django.middleware.locale.LocaleMiddleware` (and keep `USE_I18N = True`) if you
139
+ want the docs to follow the request's language.
140
+
141
+ ## Development
142
+
143
+ ```
144
+ poetry install
145
+ poetry run python manage.py test tests
146
+ ```
147
+
148
+ Run the full support matrix with [tox](https://tox.wiki):
149
+
150
+ ```
151
+ poetry run tox
152
+ ```
153
+
154
+ See [CONTRIBUTING.md](CONTRIBUTING.md) for coverage, translations, and the
155
+ pull-request checklist.
156
+
157
+ ## License
158
+
159
+ MIT
File without changes
@@ -0,0 +1,6 @@
1
+ from django.apps import AppConfig
2
+
3
+
4
+ class DocsViewerConfig(AppConfig):
5
+ name = "docs_viewer"
6
+ verbose_name = "Documentation Viewer"
@@ -0,0 +1,28 @@
1
+ from django.conf import settings
2
+ from django.utils.translation import gettext_lazy as _
3
+
4
+ DEFAULT_TITLE = _("Documentation")
5
+ DEFAULT_BASE_TEMPLATE = "docs_viewer/base.html"
6
+ DEFAULT_TOC_DEPTH = "2-3"
7
+ DEFAULT_SKIP_DIRS = ["_*"]
8
+
9
+
10
+ def login_required():
11
+ return getattr(settings, "DOCS_VIEWER_LOGIN_REQUIRED", True)
12
+
13
+
14
+ def default_title():
15
+ return getattr(settings, "DOCS_VIEWER_TITLE", DEFAULT_TITLE)
16
+
17
+
18
+ def base_template():
19
+ return getattr(settings, "DOCS_VIEWER_BASE_TEMPLATE", DEFAULT_BASE_TEMPLATE)
20
+
21
+
22
+ def toc_depth():
23
+ return getattr(settings, "DOCS_VIEWER_TOC_DEPTH", DEFAULT_TOC_DEPTH)
24
+
25
+
26
+ def skip_dirs():
27
+ """Glob patterns; a page is hidden when any directory in its path matches one."""
28
+ return getattr(settings, "DOCS_VIEWER_SKIP_DIRS", DEFAULT_SKIP_DIRS)
@@ -0,0 +1,21 @@
1
+ msgid ""
2
+ msgstr ""
3
+ "Project-Id-Version: django-docs-viewer\n"
4
+ "Report-Msgid-Bugs-To: \n"
5
+ "POT-Creation-Date: 2026-07-28 14:46+0200\n"
6
+ "PO-Revision-Date: 2026-07-28 00:00+0000\n"
7
+ "Last-Translator: \n"
8
+ "Language-Team: German\n"
9
+ "Language: de\n"
10
+ "MIME-Version: 1.0\n"
11
+ "Content-Type: text/plain; charset=UTF-8\n"
12
+ "Content-Transfer-Encoding: 8bit\n"
13
+ "Plural-Forms: nplurals=2; plural=(n != 1);\n"
14
+
15
+ #: conf.py:4
16
+ msgid "Documentation"
17
+ msgstr "Dokumentation"
18
+
19
+ #: templates/docs_viewer/detail.html:27
20
+ msgid "Back"
21
+ msgstr "Zurück"
@@ -0,0 +1,21 @@
1
+ msgid ""
2
+ msgstr ""
3
+ "Project-Id-Version: django-docs-viewer\n"
4
+ "Report-Msgid-Bugs-To: \n"
5
+ "POT-Creation-Date: 2026-07-28 14:46+0200\n"
6
+ "PO-Revision-Date: 2026-07-28 00:00+0000\n"
7
+ "Last-Translator: \n"
8
+ "Language-Team: English\n"
9
+ "Language: en\n"
10
+ "MIME-Version: 1.0\n"
11
+ "Content-Type: text/plain; charset=UTF-8\n"
12
+ "Content-Transfer-Encoding: 8bit\n"
13
+ "Plural-Forms: nplurals=2; plural=(n != 1);\n"
14
+
15
+ #: conf.py:4
16
+ msgid "Documentation"
17
+ msgstr "Documentation"
18
+
19
+ #: templates/docs_viewer/detail.html:27
20
+ msgid "Back"
21
+ msgstr "Back"
@@ -0,0 +1,21 @@
1
+ msgid ""
2
+ msgstr ""
3
+ "Project-Id-Version: django-docs-viewer\n"
4
+ "Report-Msgid-Bugs-To: \n"
5
+ "POT-Creation-Date: 2026-07-28 14:46+0200\n"
6
+ "PO-Revision-Date: 2026-07-28 00:00+0000\n"
7
+ "Last-Translator: \n"
8
+ "Language-Team: French\n"
9
+ "Language: fr\n"
10
+ "MIME-Version: 1.0\n"
11
+ "Content-Type: text/plain; charset=UTF-8\n"
12
+ "Content-Transfer-Encoding: 8bit\n"
13
+ "Plural-Forms: nplurals=2; plural=(n > 1);\n"
14
+
15
+ #: conf.py:4
16
+ msgid "Documentation"
17
+ msgstr "Documentation"
18
+
19
+ #: templates/docs_viewer/detail.html:27
20
+ msgid "Back"
21
+ msgstr "Retour"
@@ -0,0 +1,94 @@
1
+ import re
2
+
3
+ from django.urls import reverse
4
+ from django.utils.html import escape
5
+
6
+ from .pages import (
7
+ MENU_FILE,
8
+ dedicated_index,
9
+ discover_pages,
10
+ is_index_filename,
11
+ page_heading,
12
+ render_markdown,
13
+ )
14
+ from .paths import docs_root, without_markdown_suffix
15
+
16
+ _NUMERIC_PREFIX_PATTERN = re.compile(r"^(\d+)[-_ ]")
17
+
18
+
19
+ def build_sidebar_html(current_path):
20
+ menu_file = docs_root() / MENU_FILE
21
+ if menu_file.is_file():
22
+ return render_markdown(menu_file)
23
+
24
+ root_pages, groups = _group_pages(discover_pages())
25
+ parts = ['<ul class="docs-nav">']
26
+
27
+ if home_link := _home_link(current_path):
28
+ parts.append(home_link)
29
+
30
+ for page in sorted(root_pages, key=_page_sort_key):
31
+ parts.append(_page_link(page, current_path))
32
+
33
+ for group in sorted(groups, key=str.lower):
34
+ parts.append(f'<li class="docs-nav-group"><span>{escape(_humanize(group))}</span><ul>')
35
+ for page in sorted(groups[group], key=_page_sort_key):
36
+ parts.append(_page_link(page, current_path))
37
+ parts.append("</ul></li>")
38
+
39
+ parts.append("</ul>")
40
+ return "".join(parts)
41
+
42
+
43
+ def _group_pages(pages):
44
+ """Partition discovered pages into top-level pages and folder groups keyed by folder name."""
45
+ root = docs_root()
46
+ root_pages = []
47
+ groups = {}
48
+ for page in pages:
49
+ relative = page.relative_to(root)
50
+ if len(relative.parts) == 1:
51
+ root_pages.append(page) # flat docs: pages live directly under the docs directory
52
+ else:
53
+ groups.setdefault(relative.parts[0], []).append(page)
54
+ return root_pages, groups
55
+
56
+
57
+ def _home_link(current_path):
58
+ """The top-level index/README, linked to the docs home. Skipped when the landing is just the
59
+ first discovered page (no dedicated index) — that page is already listed in the nav."""
60
+ index = dedicated_index()
61
+ if index is None:
62
+ return None
63
+ return _nav_link(
64
+ reverse("docs:home"),
65
+ _page_label(docs_root() / index),
66
+ is_active=current_path == without_markdown_suffix(index),
67
+ )
68
+
69
+
70
+ def _page_link(page, current_path):
71
+ doc_path = without_markdown_suffix(page.relative_to(docs_root()).as_posix())
72
+ return _nav_link(
73
+ reverse("docs:detail", kwargs={"doc_path": doc_path}),
74
+ _page_label(page),
75
+ is_active=doc_path == current_path,
76
+ )
77
+
78
+
79
+ def _nav_link(href, label, is_active):
80
+ active = " active" if is_active else ""
81
+ return f'<li><a class="docs-nav-link{active}" href="{href}">{escape(label)}</a></li>'
82
+
83
+
84
+ def _page_label(page):
85
+ """The page's first level-1 heading, or a humanized filename when it has none."""
86
+ return page_heading(page) or _humanize(page.stem)
87
+
88
+
89
+ def _humanize(name):
90
+ return _NUMERIC_PREFIX_PATTERN.sub("", name).replace("-", " ").replace("_", " ").title()
91
+
92
+
93
+ def _page_sort_key(page):
94
+ return (0 if is_index_filename(page.name) else 1, page.name.lower())
@@ -0,0 +1,102 @@
1
+ import fnmatch
2
+ import re
3
+ from pathlib import Path
4
+
5
+ import markdown
6
+
7
+ from .conf import default_title, skip_dirs, toc_depth
8
+ from .paths import docs_root
9
+
10
+ MARKDOWN_EXTENSIONS = ["fenced_code", "tables", "toc", "sane_lists"]
11
+
12
+ MENU_FILE = "menu.md"
13
+ # Matched case-insensitively for the docs-root landing page; also lead each folder's navigation
14
+ # group, ahead of the ordered pages. Kept lowercase and ordered by preference.
15
+ INDEX_FILENAMES = ["index.md", "readme.md"]
16
+
17
+ _HEADING_PATTERN = re.compile(r"^\s*#\s+(.+?)\s*$", re.MULTILINE)
18
+
19
+
20
+ def is_hidden(relative_path):
21
+ """True when any directory in the path matches a configured skip pattern (see DOCS_VIEWER_SKIP_DIRS)."""
22
+ directories = Path(relative_path).parts[:-1]
23
+ return any(fnmatch.fnmatch(part, pattern) for part in directories for pattern in skip_dirs())
24
+
25
+
26
+ def _converter():
27
+ return markdown.Markdown(
28
+ extensions=MARKDOWN_EXTENSIONS,
29
+ extension_configs={"toc": {"toc_depth": toc_depth()}},
30
+ )
31
+
32
+
33
+ def render_markdown(page):
34
+ # Rendered from repo-authored, trusted markdown; templates inject the result with |safe.
35
+ return _converter().convert(page.read_text(encoding="utf-8"))
36
+
37
+
38
+ def render_page(page):
39
+ """Render a page to (content_html, toc_html); toc_html is empty when the page has no sub-headings."""
40
+ converter = _converter()
41
+ content_html = converter.convert(page.read_text(encoding="utf-8"))
42
+ toc_html = converter.toc if converter.toc_tokens else ""
43
+ return content_html, toc_html
44
+
45
+
46
+ def page_heading(page):
47
+ """The page's first level-1 heading, or None when it has none."""
48
+ match = _HEADING_PATTERN.search(page.read_text(encoding="utf-8"))
49
+ return match.group(1) if match else None
50
+
51
+
52
+ def is_index_filename(name):
53
+ return name.lower() in INDEX_FILENAMES
54
+
55
+
56
+ def is_top_level_index(relative_path):
57
+ """True for a landing-page file (index/README) sitting directly at the docs root."""
58
+ relative = Path(relative_path)
59
+ return relative.parent == Path() and is_index_filename(relative.name)
60
+
61
+
62
+ def discover_pages():
63
+ root = docs_root()
64
+ pages = []
65
+ for page in root.rglob("*.md"):
66
+ relative = page.relative_to(root)
67
+ if is_hidden(relative) or page.name == MENU_FILE:
68
+ continue
69
+ # The top-level index/README is the landing page, not a nav entry.
70
+ if is_top_level_index(relative):
71
+ continue
72
+ pages.append(page)
73
+ return pages
74
+
75
+
76
+ def dedicated_index():
77
+ """The docs-root index/README landing file, matched case-insensitively; None when absent."""
78
+ root = docs_root()
79
+ if not root.is_dir():
80
+ return None
81
+ by_name = {child.name.lower(): child.name for child in root.iterdir() if child.is_file()}
82
+ for candidate in INDEX_FILENAMES:
83
+ if candidate in by_name:
84
+ return by_name[candidate]
85
+ return None
86
+
87
+
88
+ def landing_relative_path():
89
+ index = dedicated_index()
90
+ if index is not None:
91
+ return index
92
+ pages = discover_pages()
93
+ return pages[0].relative_to(docs_root()).as_posix() if pages else None
94
+
95
+
96
+ def site_title():
97
+ """The docs title, taken from the index page's heading; a default when there is no index."""
98
+ default = default_title()
99
+ index = dedicated_index()
100
+ if index is None:
101
+ return default
102
+ return page_heading(docs_root() / index) or default
@@ -0,0 +1,57 @@
1
+ from pathlib import Path
2
+
3
+ from django.conf import settings
4
+ from django.core.exceptions import SuspiciousFileOperation
5
+ from django.http import Http404
6
+ from django.utils._os import safe_join
7
+
8
+ IMAGE_SUFFIXES = {".png", ".jpg", ".jpeg", ".svg", ".gif"}
9
+ MARKDOWN_SUFFIX = ".md"
10
+
11
+
12
+ def docs_root():
13
+ return Path(settings.DOCS_VIEWER_ROOT)
14
+
15
+
16
+ def resolve_within_docs(relative_path):
17
+ """Resolve a URL path against the docs directory case-insensitively, guarding against traversal.
18
+
19
+ Returns the matching on-disk path with its real casing, or None when nothing matches.
20
+ """
21
+ root = docs_root()
22
+ try:
23
+ requested = Path(safe_join(str(root), relative_path))
24
+ except (ValueError, SuspiciousFileOperation):
25
+ raise Http404("Path outside documentation directory")
26
+
27
+ resolved = root
28
+ for part in requested.relative_to(root).parts:
29
+ resolved = _matching_child(resolved, part)
30
+ if resolved is None:
31
+ return None
32
+ return resolved
33
+
34
+
35
+ def _matching_child(directory, name):
36
+ """The entry of directory whose name matches name case-insensitively, or None."""
37
+ if not directory.is_dir():
38
+ return None
39
+ lowered = name.lower()
40
+ for child in directory.iterdir():
41
+ if child.name.lower() == lowered:
42
+ return child
43
+ return None
44
+
45
+
46
+ def is_image_request(doc_path):
47
+ return Path(doc_path).suffix.lower() in IMAGE_SUFFIXES
48
+
49
+
50
+ def with_markdown_suffix(doc_path):
51
+ return f"{without_markdown_suffix(doc_path)}{MARKDOWN_SUFFIX}"
52
+
53
+
54
+ def without_markdown_suffix(doc_path):
55
+ if doc_path.lower().endswith(MARKDOWN_SUFFIX):
56
+ return doc_path[: -len(MARKDOWN_SUFFIX)]
57
+ return doc_path
@@ -0,0 +1,11 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <title>{% block title %}{{ site_title }}{% endblock %}</title>
7
+ </head>
8
+ <body>
9
+ {% block content %}{% endblock %}
10
+ </body>
11
+ </html>
@@ -0,0 +1,34 @@
1
+ {% extends base_template %}
2
+ {% load i18n %}
3
+
4
+ {% block title %}{{ site_title }}{% endblock %}
5
+
6
+ {% block content %}
7
+ <style>
8
+ .docs-header { display: flex; justify-content: space-between; align-items: baseline; gap: 1rem; max-width: 60rem; margin: 0 auto; padding: 1rem 1rem 0; }
9
+ .docs-title { margin: 0; }
10
+ .docs-back { text-decoration: none; white-space: nowrap; }
11
+ .docs-layout { display: flex; gap: 2rem; align-items: flex-start; max-width: 60rem; margin: 0 auto; padding: 1rem; }
12
+ .docs-sidebar { flex: 0 0 14rem; }
13
+ .docs-content { flex: 1 1 auto; min-width: 0; }
14
+ .docs-toc { flex: 0 0 12rem; position: sticky; top: 1rem; font-size: .9rem; }
15
+ .docs-toc .toc > ul, .docs-toc .toc ul { list-style: none; padding-left: 0; }
16
+ .docs-toc .toc ul ul { padding-left: 1rem; }
17
+ .docs-toc a { text-decoration: none; }
18
+ .docs-nav, .docs-nav ul { list-style: none; padding-left: 0; }
19
+ .docs-nav ul { padding-left: 1rem; }
20
+ .docs-nav-group > span { font-weight: 600; display: block; margin-top: .75rem; }
21
+ .docs-nav-link { text-decoration: none; }
22
+ .docs-nav-link.active { font-weight: 600; }
23
+ .docs-content img { max-width: 100%; height: auto; }
24
+ </style>
25
+ <header class="docs-header">
26
+ <h1 class="docs-title">{{ site_title }}</h1>
27
+ <a class="docs-back" href="/">&larr; {% translate "Back" %}</a>
28
+ </header>
29
+ <div class="docs-layout">
30
+ <nav class="docs-sidebar">{{ sidebar_html|safe }}</nav>
31
+ <article class="docs-content">{{ content_html|safe }}</article>
32
+ {% if toc_html %}<aside class="docs-toc">{{ toc_html|safe }}</aside>{% endif %}
33
+ </div>
34
+ {% endblock %}
@@ -0,0 +1,10 @@
1
+ from django.urls import path
2
+
3
+ from .views import DocsView
4
+
5
+ app_name = "docs"
6
+
7
+ urlpatterns = [
8
+ path("", DocsView.as_view(), name="home"),
9
+ path("<path:doc_path>", DocsView.as_view(), name="detail"),
10
+ ]
@@ -0,0 +1,60 @@
1
+ from django.contrib.auth.views import redirect_to_login
2
+ from django.http import Http404
3
+ from django.shortcuts import render
4
+ from django.views import View
5
+ from django.views.static import serve
6
+
7
+ from .conf import base_template, login_required
8
+ from .navigation import build_sidebar_html
9
+ from .pages import is_hidden, landing_relative_path, render_page, site_title
10
+ from .paths import (
11
+ docs_root,
12
+ is_image_request,
13
+ resolve_within_docs,
14
+ with_markdown_suffix,
15
+ without_markdown_suffix,
16
+ )
17
+
18
+
19
+ class DocsView(View):
20
+ def dispatch(self, request, *args, **kwargs):
21
+ if login_required() and not request.user.is_authenticated:
22
+ return redirect_to_login(request.get_full_path())
23
+ return super().dispatch(request, *args, **kwargs)
24
+
25
+ def get(self, request, doc_path=""):
26
+ if is_image_request(doc_path):
27
+ image = resolve_within_docs(doc_path)
28
+ if image is None or not image.is_file() or is_hidden(image.relative_to(docs_root())):
29
+ raise Http404("Documentation page not found")
30
+ return serve(request, image.relative_to(docs_root()).as_posix(), document_root=str(docs_root()))
31
+
32
+ if not doc_path:
33
+ relative_path = landing_relative_path()
34
+ if relative_path is None:
35
+ raise Http404("No documentation available")
36
+ else:
37
+ # An optional .md suffix lets relative links between Markdown pages resolve to a sibling page.
38
+ relative_path = with_markdown_suffix(doc_path)
39
+
40
+ markdown_path = resolve_within_docs(relative_path)
41
+ if markdown_path is None or not markdown_path.is_file():
42
+ raise Http404("Documentation page not found")
43
+
44
+ relative = markdown_path.relative_to(docs_root())
45
+ if is_hidden(relative):
46
+ raise Http404("Documentation page not found")
47
+
48
+ canonical_path = without_markdown_suffix(relative.as_posix())
49
+ content_html, toc_html = render_page(markdown_path)
50
+ return render(
51
+ request,
52
+ "docs_viewer/detail.html",
53
+ {
54
+ "base_template": base_template(),
55
+ "site_title": site_title(),
56
+ "content_html": content_html,
57
+ "toc_html": toc_html,
58
+ "sidebar_html": build_sidebar_html(canonical_path),
59
+ },
60
+ )
@@ -0,0 +1,71 @@
1
+ [project]
2
+ name = "django-docs-viewer"
3
+ version = "0.1.0"
4
+ description = "A simple in-app Markdown documentation viewer for Django."
5
+ authors = [{ name = "Malte Gerth", email = "mail@malte-gerth.de" }]
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ readme = "README.md"
9
+ keywords = ["django", "documentation", "markdown", "docs"]
10
+ requires-python = ">=3.10"
11
+ classifiers = [
12
+ "Development Status :: 4 - Beta",
13
+ "Environment :: Web Environment",
14
+ "Framework :: Django",
15
+ "Framework :: Django :: 4",
16
+ "Framework :: Django :: 4.2",
17
+ "Framework :: Django :: 5",
18
+ "Framework :: Django :: 5.0",
19
+ "Framework :: Django :: 5.1",
20
+ "Framework :: Django :: 5.2",
21
+ "Framework :: Django :: 6.0",
22
+ "Intended Audience :: Developers",
23
+ "Programming Language :: Python",
24
+ "Programming Language :: Python :: 3.10",
25
+ "Programming Language :: Python :: 3.11",
26
+ "Programming Language :: Python :: 3.12",
27
+ "Programming Language :: Python :: 3.13",
28
+ "Programming Language :: Python :: 3.14",
29
+ "Topic :: Documentation",
30
+ "Topic :: Software Development :: Libraries",
31
+ "Topic :: Software Development :: Libraries :: Application Frameworks",
32
+ "Topic :: Software Development :: Libraries :: Python Modules",
33
+ ]
34
+ dependencies = [
35
+ "django>=4.2",
36
+ "markdown>=3.4",
37
+ ]
38
+
39
+ [project.urls]
40
+ Homepage = "https://github.com/JanMalte/django-docs-viewer"
41
+ Repository = "https://github.com/JanMalte/django-docs-viewer"
42
+ Documentation = "https://github.com/JanMalte/django-docs-viewer"
43
+
44
+ [tool.poetry]
45
+ packages = [
46
+ { include = "docs_viewer" },
47
+ ]
48
+
49
+ [tool.poetry.group.dev.dependencies]
50
+ coverage = ">=7.0"
51
+ pre-commit = ">=3.5"
52
+ tox = ">=4.0"
53
+ ruff = ">=0.6"
54
+
55
+ [build-system]
56
+ requires = ["poetry-core>=2.0.0"]
57
+ build-backend = "poetry.core.masonry.api"
58
+
59
+ [tool.ruff]
60
+ line-length = 120
61
+
62
+ [tool.ruff.lint]
63
+ extend-select = ["E501", "UP", "I", "DJ"]
64
+
65
+ [tool.coverage.run]
66
+ branch = true
67
+ source = ["docs_viewer/"]
68
+
69
+ [tool.coverage.report]
70
+ show_missing = true
71
+ exclude_lines = ["pragma: no cover"]