add: шаблон для ошибки (1) 404

This commit is contained in:
2026-09-14 00:02:45 +03:00
parent c7ed8235ed
commit 2e11b536cb
7 changed files with 652 additions and 6 deletions
+5
View File
@@ -30,6 +30,11 @@ urlpatterns = [
path('', include('hypn0_site.urls')),
]
handler400 = "hypn0_site.views.error_400"
handler403 = "hypn0_site.views.error_403"
handler404 = "hypn0_site.views.error_404"
handler500 = "hypn0_site.views.error_500"
if settings.DEBUG:
import mimetypes
import debug_toolbar
+35
View File
@@ -1425,3 +1425,38 @@ class BlogPostModelAndAdminTests(BaseMediaTestCase):
# 5. Проверка 404 для несуществующего слага
resp_404 = self.client.get("/blog/non-existent-slug-xyz")
self.assertEqual(resp_404.status_code, 404)
@override_settings(DEBUG=False)
def test_custom_404_page_rendering(self):
"""Проверка отдачи кастомной страницы 404 в режиме DEBUG=False."""
response = self.client.get("/totally-non-existent-hypno-route-404")
self.assertEqual(response.status_code, 404)
self.assertContains(response, "Гипноузел не обнаружен", status_code=404)
self.assertContains(response, "СБОЙ МАТРИЦЫ // КОД? 404", status_code=404)
self.assertContains(response, "return-btn", status_code=404)
self.assertContains(response, "Стираем остатки несущес­твующей страницы", status_code=404)
@override_settings(DEBUG=True)
def test_debug_error_preview_routing(self):
"""Проверка dev-маршрутизации предпросмотра страниц ошибок при DEBUG=True."""
# 1. Индексный список страниц ошибок
resp_list = self.client.get("/_error/")
self.assertEqual(resp_list.status_code, 200)
self.assertContains(resp_list, "Центр отладки страниц ошибок")
self.assertContains(resp_list, "/_error/404")
# 2. Предпросмотр конкретной ошибки 404
resp_404 = self.client.get("/_error/404")
self.assertEqual(resp_404.status_code, 404)
self.assertContains(resp_404, "Гипноузел не обнаружен", status_code=404)
self.assertContains(resp_404, "СБОЙ МАТРИЦЫ // КОД? 404", status_code=404)
# 3. Предпросмотр с суффиксом .html
resp_404_html = self.client.get("/_error/404.html")
self.assertEqual(resp_404_html.status_code, 404)
self.assertContains(resp_404_html, "Гипноузел не обнаружен", status_code=404)
# 4. Несуществующий шаблон ошибки в dev-режиме
resp_non_existent = self.client.get("/_error/non-existent-code-999")
self.assertEqual(resp_non_existent.status_code, 404)
self.assertContains(resp_non_existent, "Шаблон для ошибки 'non-existent-code-999' не найден", status_code=404)
+6 -1
View File
@@ -19,4 +19,9 @@ urlpatterns = [
]
if settings.DEBUG:
urlpatterns += [path("tmp/", views.tmp, name="web_tmp")]
urlpatterns += [
path("tmp/", views.tmp, name="web_tmp"),
path("_error", views.debug_error_preview, name="debug_error_list"),
path("_error/", views.debug_error_preview, name="debug_error_list_slash"),
path("_error/<path:code>", views.debug_error_preview, name="debug_error_preview"),
]
+113
View File
@@ -157,6 +157,119 @@ def tmp(request: HttpRequest | None) -> HttpResponse:
return render(request, "tmp.html", {})
def debug_error_preview(request: HttpRequest, code: str = "") -> HttpResponse:
"""
Dev-представление для отладки и предпросмотра страниц ошибок в режиме DEBUG.
Поддерживает пути вида /_error/404, /_error/404.html, /_error/500, /_error/, /_error/under_reconstruction.
"""
from django.template.exceptions import TemplateDoesNotExist
from django.template.loader import get_template
# Очистка имени шаблона от расширения .html и слэшей
raw_name = code.strip("/").removesuffix(".html") if code else ""
available_codes = [
"400",
"401",
"403",
"404",
"413",
"429",
"500",
"502",
"503",
"504",
"under_reconstruction",
]
if not raw_name:
# Индексная страница со списком всех кодов ошибок для dev-отладки
links = []
for c in available_codes:
exists = False
for tpl in [f"_error/{c}.html", f"{c}.html"]:
try:
get_template(tpl)
exists = True
break
except TemplateDoesNotExist:
pass
status_mark = "готов к просмотру" if exists else "шаблон не создан"
links.append(f"<li><a href='/_error/{c}'><strong>/{c}</strong></a> ({status_mark})</li>")
html = f"""<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8">
<title>Dev: Предпросмотр страниц ошибок // HypnoSVG</title>
<style>
body {{ font-family: ui-monospace, monospace; background: #09090b; color: #d9f99d; padding: 2rem; line-height: 1.6; }}
a {{ color: #a3e635; text-decoration: none; border-bottom: 1px dotted #a3e635; }}
a:hover {{ border-bottom-style: solid; }}
ul {{ list-style-type: square; margin-top: 1rem; }}
li {{ margin-bottom: 0.5rem; }}
.card {{ background: #18181b; border: 1px solid #27272a; border-radius: 8px; padding: 1.5rem; max-width: 600px; }}
</style>
</head>
<body>
<div class="card">
<h2>Центр отладки страниц ошибок (DEBUG=True)</h2>
<p>Выберите код для инспекции верстки и интерактивных скриптов перекалибровки:</p>
<ul>
{''.join(links)}
</ul>
</div>
</body>
</html>"""
return HttpResponse(html, content_type="text/html; charset=utf-8")
# Поиск соответствующего шаблона
template_candidates = [
f"_error/{raw_name}.html",
f"{raw_name}.html",
f"_error/{raw_name}",
raw_name,
]
found_template = None
for candidate in template_candidates:
try:
get_template(candidate)
found_template = candidate
break
except TemplateDoesNotExist:
continue
if not found_template:
return HttpResponse(
f"<h1>Шаблон для ошибки '{raw_name}' не найден</h1><p>Проверены: {', '.join(template_candidates)}</p><p><a href='/_error/'>← Вернуться к списку</a></p>",
status=404,
content_type="text/html; charset=utf-8",
)
status_code = 200
if raw_name.isdigit() and 400 <= int(raw_name) <= 599:
status_code = int(raw_name)
return render(request, found_template, {}, status=status_code)
def error_400(request: HttpRequest, exception: Exception | None = None) -> HttpResponse:
return render(request, "_error/400.html", {}, status=400)
def error_403(request: HttpRequest, exception: Exception | None = None) -> HttpResponse:
return render(request, "_error/403.html", {}, status=403)
def error_404(request: HttpRequest, exception: Exception | None = None) -> HttpResponse:
return render(request, "_error/404.html", {}, status=404)
def error_500(request: HttpRequest) -> HttpResponse:
return render(request, "_error/500.html", {}, status=500)
@require_POST
def generate(request: HttpRequest) -> HttpResponse:
"""
+480
View File
@@ -0,0 +1,480 @@
<!doctype html>
<html lang="ru">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>404 — Векторная реальность не найдена | HypnoSVG</title>
<meta name="description" content="Ошибка 404: Запрашиваемая страница не существует или стёрта волей Гипножабы." />
<meta name="robots" content="noindex, follow" />
<link rel="icon" type="image/svg+xml" href="/static/img/favicon.svg" />
<link rel="shortcut icon" href="/static/img/favicon.ico" />
<script>
(function() {
var saved = localStorage.getItem('darkMode');
var prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
if (saved === 'true' || (saved === null && prefersDark)) {
document.documentElement.classList.add('dark');
} else {
document.documentElement.classList.remove('dark');
}
})();
</script>
<style>
:root {
--bg-color: #fafaf9;
--bg-header: rgba(243, 244, 246, 0.85);
--bg-card: #ffffff;
--text-main: #047857;
--text-muted: #4b5563;
--text-dim: #9ca3af;
--border-color: #d1d5db;
--accent-color: #059669;
--accent-hover: #047857;
--accent-bg: #ecfdf5;
--btn-bg: #059669;
--btn-text: #ffffff;
--btn-hover: #047857;
--glitch-color: #dc2626;
--progress-bg: #e5e7eb;
--progress-fill: #059669;
}
html.dark {
--bg-color: #09090b;
--bg-header: rgba(30, 41, 59, 0.75);
--bg-card: #18181b;
--text-main: #d9f99d;
--text-muted: #a1a1aa;
--text-dim: #71717a;
--border-color: #27272a;
--accent-color: #a3e635;
--accent-hover: #bef264;
--accent-bg: #14280f;
--btn-bg: #a3e635;
--btn-text: #09090b;
--btn-hover: #bef264;
--glitch-color: #f87171;
--progress-bg: #27272a;
--progress-fill: #a3e635;
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
background-color: var(--bg-color);
color: var(--text-main);
min-height: 100vh;
display: flex;
flex-direction: column;
line-height: 1.6;
transition: background-color 0.3s ease, color 0.3s ease;
}
header {
position: sticky;
top: 0;
z-index: 50;
background-color: var(--bg-header);
backdrop-filter: blur(8px);
-webkit-backdrop-filter: blur(8px);
border-bottom: 1px solid var(--border-color);
padding: 0.75rem 1rem;
}
.header-inner {
max-width: 80rem;
margin: 0 auto;
display: flex;
justify-content: space-between;
align-items: center;
}
.logo-link {
display: inline-flex;
align-items: center;
text-decoration: none;
border: 0;
}
.logo-img {
height: 2.25rem;
width: auto;
display: block;
}
.theme-toggle {
background: transparent;
border: 1px solid var(--border-color);
color: var(--text-main);
border-radius: 0.5rem;
padding: 0.4rem 0.8rem;
font-size: 1.1rem;
cursor: pointer;
font-family: inherit;
transition: background-color 0.2s ease, border-color 0.2s ease;
}
.theme-toggle:hover {
background-color: var(--accent-bg);
border-color: var(--accent-color);
}
main {
flex: 1;
max-width: 56rem;
width: 100%;
margin: 0 auto;
padding: 2.5rem 1rem 4rem;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
text-align: center;
}
.error-card {
background-color: var(--bg-card);
border: 1px solid var(--border-color);
border-radius: 1rem;
padding: 2.5rem 1.75rem;
width: 100%;
box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.05), 0 8px 10px -6px rgba(0, 0, 0, 0.02);
position: relative;
overflow: hidden;
}
.error-art {
width: 300px;
height: 300px;
margin: 0 auto 1.5rem;
display: flex;
/* align-items: center;
justify-content: center; */
}
.error-art img, .error-art svg {
width: 100%;
height: 100%;
object-fit: contain;
}
@keyframes pulse-art {
0%, 100% { transform: scale(1) rotate(0deg); }
50% { transform: scale(1.05) rotate(-2deg); }
}
.error-code-badge {
display: inline-block;
font-size: 0.875rem;
font-weight: 700;
letter-spacing: 0.1em;
text-transform: uppercase;
padding: 0.25rem 0.75rem;
border-radius: 9999px;
background-color: var(--accent-bg);
color: var(--accent-color);
border: 1px solid var(--accent-color);
margin-bottom: 1rem;
}
.error-title {
font-size: clamp(1.75rem, 4vw, 2.5rem);
font-weight: 800;
line-height: 1.2;
margin-bottom: 1rem;
letter-spacing: -0.02em;
}
.error-desc {
color: var(--text-muted);
font-size: 1.05rem;
max-width: 40rem;
margin: 0 auto 2rem;
line-height: 1.7;
}
.hypno-quote {
background-color: var(--accent-bg);
border-left: 4px solid var(--accent-color);
padding: 0.875rem 1.25rem;
margin: 0 auto 2rem;
text-align: left;
font-size: 0.925rem;
color: var(--text-muted);
border-radius: 0 0.5rem 0.5rem 0;
max-width: 42rem;
}
.actions-box {
margin-top: 1.5rem;
display: flex;
flex-direction: column;
align-items: center;
gap: 1rem;
}
.btn-group {
display: flex;
flex-wrap: wrap;
gap: 0.875rem;
justify-content: center;
width: 100%;
}
.btn {
font-family: inherit;
font-size: 1rem;
font-weight: 600;
padding: 0.85rem 1.75rem;
border-radius: 0.625rem;
border: 1px solid transparent;
cursor: pointer;
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.5rem;
text-decoration: none;
transition: all 0.2s ease;
min-width: 16rem;
}
.btn-primary {
background-color: var(--btn-bg);
color: var(--btn-text);
box-shadow: 0 4px 14px 0 rgba(5, 150, 105, 0.25);
}
.btn-primary:hover:not(:disabled) {
background-color: var(--btn-hover);
transform: translateY(-1px);
}
.btn-primary:disabled {
opacity: 0.85;
cursor: wait;
transform: none;
}
.btn-secondary {
background-color: transparent;
color: var(--text-main);
border-color: var(--border-color);
}
.btn-secondary:hover:not(:disabled) {
background-color: var(--accent-bg);
border-color: var(--accent-color);
}
/* Задержка и смешные сообщения перекалибровки */
.calibration-panel {
display: none;
width: 100%;
max-width: 32rem;
margin-top: 1.25rem;
padding: 1rem 1.25rem;
border-radius: 0.75rem;
background-color: var(--accent-bg);
border: 1px dashed var(--accent-color);
text-align: left;
animation: fadeIn 0.3s ease;
}
@keyframes fadeIn {
from { opacity: 0; transform: translateY(6px); }
to { opacity: 1; transform: translateY(0); }
}
.progress-bar-container {
width: 100%;
height: 8px;
background-color: var(--progress-bg);
border-radius: 4px;
overflow: hidden;
margin: 0.75rem 0;
}
.progress-bar-fill {
height: 100%;
width: 0%;
background-color: var(--progress-fill);
transition: width 0.1s linear;
}
.calibration-status {
font-size: 0.875rem;
font-weight: 600;
color: var(--text-main);
min-height: 1.5rem;
}
.calibration-subtext {
font-size: 0.775rem;
color: var(--text-dim);
display: flex;
justify-content: space-between;
align-items: center;
margin-top: 0.5rem;
}
.instant-link {
color: var(--accent-color);
text-decoration: underline;
cursor: pointer;
font-size: 0.775rem;
}
footer {
border-top: 1px solid var(--border-color);
padding: 1.5rem 1rem;
text-align: center;
font-size: 0.825rem;
color: var(--text-dim);
}
.ascii-grid {
font-size: 0.75rem;
line-height: 1.2;
color: var(--text-dim);
opacity: 0.4;
user-select: none;
margin-bottom: 1rem;
overflow: hidden;
white-space: pre;
}
</style>
</head>
<body>
<header>
<div class="header-inner">
<a href="/" class="logo-link" title="HypnoSVG (hypn0) — На главную">
<img src="/static/img/logo-hypn0.svg" onerror="this.onerror=null; this.src='/media/_error/logo-hypn0.svg';" alt="HypnoSVG" class="logo-img" />
</a>
<button type="button" class="theme-toggle" id="theme-btn" aria-label="Переключить тему" title="Переключить тему">
<span id="theme-icon">●</span>
</button>
</div>
</header>
<main>
<div class="error-card">
<div class="error-art">
<img src="/static/img/thinking.svg" onerror="this.onerror=null; this.src='/media/_error/thinking.svg';" alt="404 Thinking Slug" />
</div>
<div class="error-code-badge">СБОЙ МАТРИЦЫ // КОД?&nbsp;404</div>
<h1 class="error-title">Гипноузел не&nbsp;обнаружен</h1>
<p class="error-desc">
Запра&shy;шиваемый блок ментального пространства стёрт из&nbsp;подсознания сервера или никогда не&nbsp;существовал в&nbsp;этой версии&nbsp;вселенной.
</p>
<div class="hypno-quote">
<big>Справка бюрократа 24-го уровня:</big><br/>&nbsp;<br/>
<span style="margin-left: -0.49em;">«</span><em>Попытка осознать отсутс&shy;твующую координату приводит к&nbsp;локальному перегреву неокортекса. Не&nbsp;вгляды&shy;вайтесь в&nbsp;пустоту. Гипножаба рекомендует немедленно сменить вектор&nbsp;внимания.</em>»
</div>
<div class="actions-box">
<div class="btn-group">
<button type="button" class="btn btn-primary" id="return-btn">
<span>● Подчиниться и&nbsp;вернуться на&nbsp;главную</span>
</button>
<button type="button" class="btn btn-secondary" onclick="window.history.length > 1 ? window.history.back() : window.location.href='/'">
<span>← На&nbsp;шаг назад</span>
</button>
</div>
<!-- Панель калибровки с задержкой и смешными фразами -->
<div class="calibration-panel" id="calibration-panel">
<div class="calibration-status" id="calibration-status">
Инициа&shy;лизация перека&shy;либровки сознания…
</div>
<div class="progress-bar-container">
<div class="progress-bar-fill" id="progress-bar"></div>
</div>
<div class="calibration-subtext">
<span>Снижение ментальной нагрузки на&nbsp;кластер</span>
<a href="/" class="instant-link" id="skip-link">Пройти гипноз мгновенно&nbsp;→</a>
</div>
</div>
</div>
</div>
</main>
<footer>
<div class="ascii-grid">░▒▓█ HYPNO-SVG // ERROR 404 NOT FOUND █▓▒░</div>
<div>Hypn0.xyz (HypnoSVG) © 2026. Слава Гипножабе. Все права подчинены.</div>
</footer>
<script>
// 1. Управление темой оформления (Light / Dark)
var themeBtn = document.getElementById('theme-btn');
var themeIcon = document.getElementById('theme-icon');
function updateThemeIcon() {
var isDark = document.documentElement.classList.contains('dark');
themeIcon.textContent = isDark ? '●' : '○';
}
updateThemeIcon();
themeBtn.addEventListener('click', function() {
var isDark = document.documentElement.classList.toggle('dark');
localStorage.setItem('darkMode', isDark);
updateThemeIcon();
});
// 2. Умная кнопка с задержкой и смешными сообщениями перекалибровки
var returnBtn = document.getElementById('return-btn');
var calibPanel = document.getElementById('calibration-panel');
var calibStatus = document.getElementById('calibration-status');
var progressBar = document.getElementById('progress-bar');
var isCalibrating = false;
var phrases = [
{ at: 0, text: "✦ Фаза 1/4: Стираем остатки несущес­твующей страницы из подсознания…" },
{ at: 25, text: "✦ Фаза 2/4: Бюрократ 24-го уровня заверяет протокол 404…" },
{ at: 55, text: "✦ Фаза 3/4: Синхронизируем частоту мерцания с перцеп­торным полем…" },
{ at: 85, text: "✦ Фаза 4/4: Внушение принято! Телепор­тация на главную…" }
];
returnBtn.addEventListener('click', function() {
if (isCalibrating) return;
isCalibrating = true;
returnBtn.disabled = true;
returnBtn.style.opacity = '0.7';
returnBtn.innerHTML = '<span>Выполняется внушение…</span>';
calibPanel.style.display = 'block';
var duration = 12000; // 7 секунд, чтобы комфортно прочитать все фазы внушения
var startTime = Date.now();
var timer = setInterval(function() {
var elapsed = Date.now() - startTime;
var progress = Math.min(100, Math.round((elapsed / duration) * 100));
progressBar.style.width = progress + '%';
// Подбираем актуальную смешную фразу
for (var i = phrases.length - 1; i >= 0; i--) {
if (progress >= phrases[i].at) {
calibStatus.textContent = phrases[i].text;
break;
}
}
if (progress >= 100) {
clearInterval(timer);
window.location.href = '/';
}
}, 50);
});
</script>
</body>
</html>
+4 -5
View File
@@ -8,8 +8,7 @@
# и служит только для сохранения структуры каталогов в репозитории.
!.gitkeep
# Лучшие SVG (храним долго)
!gallery
# Публичные, но временные, SVG (TTL 14 дней)
!temp
# Каталог _error используется для хранения пользовательских страниц ошибок. Туда все "прилетит"
# при сборке Docker-образа (и nginx будет отдавать их) и к репозитории каталог _error будет пустым
# (только с .gitkeep или .gitignore).
!_error/
+9
View File
@@ -0,0 +1,9 @@
# В этом каталоге будут храниться шаблоны ошибок (404, 500) и другие файлы необходимые для корректного
# отображения html-страниц ошибок.
#
# Все необходимые файлы "прилетят" сюда во время сборки Docker-образа из каталога hypn0/hypn0/templates/_error/
# и будут доступны по URL /media/_error/ (в проде через nginx, в dev через Django).
*.*
# Чтобы Git отслеживал пустой каталог можно использовать .gitkeep (но у нас его рель исполняет .gitignore)
!.gitkeep