mod: migrate config to env and admin url

This commit is contained in:
2026-04-08 15:16:34 +03:00
parent c481d32add
commit 0bc6de5db3
15 changed files with 606 additions and 347 deletions

View File

@@ -2,7 +2,6 @@
import ckeditor.fields
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import filer.fields.file
import taggit.managers
@@ -14,7 +13,9 @@ class Migration(migrations.Migration):
dependencies = [
('taggit', '0003_taggeditem_add_unique_index'),
('filer', '0013_auto_20221214_2211'),
# В установленной версии django-filer есть миграция 0013_image_width_height_to_float,
# а ссылка на 0013_auto_20221214_2211 относится к другой/несуществующей версии пакета.
('filer', '0013_image_width_height_to_float'),
]
operations = [

View File

@@ -1,15 +1,18 @@
# -*- coding: utf-8 -*-
import math
from django.shortcuts import render, HttpResponseRedirect
from django.http import Http404
from django.db.models import Q
from django.db.models import Count, Q
# from datetime import datetime
from django.utils import timezone
from taggit.models import Tag
from web.models import TbContent
from web.add_function import *
import pytz
# Create your views here.
def handler404(request, exception: str) -> render:
def handler404(request, exception: str):
""" Обработчик ошибки 404
:param request: http-запрос
@@ -21,7 +24,7 @@ def handler404(request, exception: str) -> render:
return response
def handler500(request) -> render:
def handler500(request):
""" Обработчик ошибки 500
:param request:
@@ -34,7 +37,7 @@ def handler500(request) -> render:
def index(request,
slug_tags: str = "",
ppage: int = 0) -> render:
ppage: int = 0):
""" Главная страница
:param request:
@@ -43,99 +46,59 @@ def index(request,
:return: response:
"""
template = "index.jinja2" # шаблон
to_template = {"COOKIES": check_cookies(request)}
# query = Q(tdContentPublishDown__isnull=True)
# query.add(Q(tdContentPublishDown__gt=timezone.now()), Q.OR)
# query.add(Q(bContentPublish=True), Q.AND)
# q_content = TbContent.objects.filter(query)[:5]
to_template: dict[str, object] = {"COOKIES": check_cookies(request)}
page_number = max(int(ppage), 0)
now_value = timezone.now()
# Базовый набор публикаций, который одинаково работает и в SQLite, и в MySQL/MariaDB.
content_qs = TbContent.objects.filter(
bContentPublish=True,
tdContentPublishUp__lte=now_value,
).filter(
Q(tdContentPublishDown__isnull=True) | Q(tdContentPublishDown__gt=now_value)
)
if slug_tags == "":
query = "SELECT web_tbcontent.* FROM web_tbcontent " \
"WHERE (web_tbcontent.tdContentPublishDown IS NULL" \
" OR web_tbcontent.tdContentPublishDown > NOW())" \
" AND web_tbcontent.tdContentPublishUp <= NOW() " \
" AND web_tbcontent.bContentPublish " \
"ORDER BY web_tbcontent.tdContentPublishUp DESC " \
"LIMIT 7 OFFSET %d" % (int(ppage) * 7, )
query_count = "SELECT 1 AS id," \
" COUNT(web_tbcontent.id) AS tot_item " \
"FROM web_tbcontent " \
"WHERE (web_tbcontent.tdContentPublishDown IS NULL" \
" OR web_tbcontent.tdContentPublishDown > NOW())" \
" AND web_tbcontent.tdContentPublishUp <= NOW()" \
" AND web_tbcontent.bContentPublish"
selected_tags: list[str] = []
else:
l_tags = slug_tags.split("_")
if sorted(l_tags) != l_tags:
# список тегов не сортирован... для поисковиков это плохо. Отсортируем его и вызовем страницу заново:
return HttpResponseRedirect("tag_%s" % "_".join(sorted(l_tags)))
s_tags = slug_tags.replace("_", "\', \'")
query = "SELECT web_tbcontent.* FROM taggit_taggeditem" \
" INNER JOIN taggit_tag" \
" ON taggit_taggeditem.tag_id = taggit_tag.id" \
" AND taggit_taggeditem.content_type_id = 21" \
" AND taggit_tag.slug IN ('%s')" \
" RIGHT OUTER JOIN web_tbcontent" \
" ON web_tbcontent.id = taggit_taggeditem.object_id " \
"WHERE (web_tbcontent.tdContentPublishDown IS NULL" \
" OR web_tbcontent.tdContentPublishDown > NOW())" \
" AND web_tbcontent.tdContentPublishUp <= NOW() " \
" AND web_tbcontent.bContentPublish " \
"GROUP BY web_tbcontent.szContentHead " \
"HAVING COUNT(DISTINCT taggit_tag.id) = %d " \
"ORDER BY web_tbcontent.tdContentPublishUp DESC " \
"LIMIT 7 OFFSET %d" % (s_tags, len(l_tags), int(ppage) * 7)
query_count = "SELECT 1 AS id," \
" COUNT(SubQuery.id) AS tot_item " \
"FROM (SELECT web_tbcontent.id" \
" FROM taggit_taggeditem" \
" INNER JOIN taggit_tag" \
" ON taggit_taggeditem.tag_id = taggit_tag.id" \
" AND taggit_taggeditem.content_type_id = 21" \
" AND taggit_tag.slug IN ('%s')" \
" RIGHT OUTER JOIN web_tbcontent" \
" ON web_tbcontent.id = taggit_taggeditem.object_id" \
" WHERE (web_tbcontent.tdContentPublishDown IS NULL" \
" OR web_tbcontent.tdContentPublishDown > NOW())" \
" AND web_tbcontent.tdContentPublishUp <= NOW()" \
" AND web_tbcontent.bContentPublish" \
" GROUP BY web_tbcontent.id" \
" HAVING COUNT(DISTINCT taggit_tag.id) = %d) SubQuery" % (s_tags, len(l_tags))
to_template.update({"TAGS_S": "/tag_" + slug_tags, "TAGS_L": l_tags})
q_content = TbContent.objects.raw(query)
q_tags = TbContent.objects.raw("SELECT DISTINCT tTotalInfo.*,"
" IF (tPageInfo.NumInPage IS UNKNOWN, 0, tPageInfo.NumInPage) AS NumInPage "
"FROM (SELECT DISTINCT taggit_tag.id, COUNT(tPage.id) AS NumInPage "
" FROM taggit_taggeditem"
" INNER JOIN taggit_tag"
" ON taggit_taggeditem.tag_id = taggit_tag.id"
" INNER JOIN (%s) tPage"
" ON taggit_taggeditem.object_id = tPage.id"
" GROUP BY taggit_tag.id) tPageInfo"
" RIGHT OUTER JOIN (SELECT DISTINCT"
" taggit_tag.*,"
" COUNT(web_tbcontent.id) AS NumTotal"
" FROM taggit_taggeditem"
" INNER JOIN taggit_tag"
" ON taggit_taggeditem.tag_id = taggit_tag.id"
" INNER JOIN web_tbcontent"
" ON taggit_taggeditem.object_id = web_tbcontent.id"
" GROUP BY taggit_tag.id, taggit_tag.name, taggit_tag.slug) tTotalInfo"
" ON tPageInfo.id = tTotalInfo.id"
" GROUP BY tPageInfo.id, tPageInfo.NumInPage,"
" tTotalInfo.id, tTotalInfo.NumTotal,"
" tTotalInfo.name, tTotalInfo.slug "
"ORDER BY tPageInfo.NumInPage DESC, tTotalInfo.NumTotal DESC, "
"tTotalInfo.name LIMIT 20" % (query,))
to_template.update({"LENTA": q_content, "TAGS_IN_PAGE": q_tags})
to_template.update({"PAGE_OF_LIST": int(ppage)})
q_count = TbContent.objects.raw(query_count)
# print("--", (q_count[0].tot_item - 1) // 7, q_count[0].tot_item)
to_template.update({"TOTAL_PAGE": (q_count[0].tot_item - 1) // 7})
selected_tags = slug_tags.split("_")
if sorted(selected_tags) != selected_tags:
# Список тегов должен быть отсортированным для канонического URL.
return HttpResponseRedirect("tag_%s" % "_".join(sorted(selected_tags)))
content_qs = content_qs.filter(tags__slug__in=selected_tags).distinct()
to_template["TAGS_S"] = "/tag_" + slug_tags
to_template["TAGS_L"] = selected_tags
q_content = content_qs.order_by("-tdContentPublishUp")
total_items = q_content.count()
total_page = max(math.ceil(total_items / 7) - 1, 0) if total_items else 0
q_content = q_content[page_number * 7: page_number * 7 + 7]
# Готовим облако тегов: общее число публикаций по каждому тегу и число публикаций на текущей странице.
page_ids = list(q_content.values_list("id", flat=True))
q_tags = (
Tag.objects.annotate(
NumTotal=Count("taggit_taggeditem_items", distinct=True),
NumInPage=Count(
"taggit_taggeditem_items",
filter=Q(taggit_taggeditem_items__object_id__in=page_ids),
distinct=True,
),
)
.filter(NumTotal__gt=0)
.order_by("-NumInPage", "-NumTotal", "name")[:20]
)
to_template["LENTA"] = q_content
to_template["TAGS_IN_PAGE"] = q_tags
to_template["PAGE_OF_LIST"] = page_number
to_template["TOTAL_PAGE"] = total_page
return render(request, template, to_template)
def redirect_item(request,
content_id: int = 0) -> render:
content_id: int = 0):
""" Переадресация URL для обеспечения переходов из поисковиков по уже проиндексированным страницам
:param request:
@@ -149,7 +112,7 @@ def redirect_item(request,
def show_item(request,
content_id: int = 0,
ppage: int = 0) -> render:
ppage: int = 0):
""" Формирование "ленты" о предприятии
:param request:
@@ -157,12 +120,14 @@ def show_item(request,
:return: response:
"""
template = "item.jinja2" # шаблон
to_template = {"COOKIES": check_cookies(request)}
to_template: dict[str, object] = {"COOKIES": check_cookies(request)}
try:
q_item = TbContent.objects.filter(id=int(content_id)).first()
if q_item is None:
raise Http404("Контента с таким id не существует")
if not q_item.bContentPublish:
raise Http404("Контент не опубликован")
to_template.update({"ITEM": q_item})
to_template["ITEM"] = q_item
# query = Q(tdContentPublishDown__isnull=True)
# query.add(Q(tdContentPublishDown__gt=timezone.now()), Q.OR)
# query.add(Q(bContentPublish=True), Q.AND)
@@ -199,14 +164,14 @@ def show_item(request,
else:
i.pp = p + 1
i.nn = n+count - 7
to_template.update({"PER_PAGE": 7})
to_template.update({"PAGE": p})
to_template["PER_PAGE"] = 7
to_template["PAGE"] = p
except ValueError:
to_template.update({"PAGE": 0})
to_template["PAGE"] = 0
pass
to_template.update({"PAGE_OF_LIST": int(ppage)})
to_template.update({"ITEMS_AFTER": q_items_after})
to_template.update({"ITEMS_BEFORE": q_items_before})
to_template["PAGE_OF_LIST"] = int(ppage)
to_template["ITEMS_AFTER"] = q_items_after
to_template["ITEMS_BEFORE"] = q_items_before
q_item.iContentHits += 1
q_item.save(update_fields=["iContentHits"])
return render(request, template, to_template)
@@ -217,9 +182,12 @@ def show_item(request,
def sitemap(request):
template = "sitemap.jinja2" # шаблон
q_items = TbContent.objects.filter(
Q(tdContentPublishDown__isnull=True) | Q(tdContentPublishDown__gt=timezone.now()),
Q(bContentPublish=True)).order_by("-tdContentPublishUp", "id").all()
to_template = {"ITEMS": q_items}
bContentPublish=True,
tdContentPublishUp__lte=timezone.now(),
).filter(
Q(tdContentPublishDown__isnull=True) | Q(tdContentPublishDown__gt=timezone.now())
).order_by("-tdContentPublishUp", "id").all()
to_template: dict[str, object] = {"ITEMS": q_items}
print(q_items)
response = render(request, template, to_template)
return response