Site/programmer/mixins.py

92 lines
3.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from typing import Any, Dict
from django.views.generic.base import ContextMixin
from .services import track_page_view
class PageViewTrackingMixin(ContextMixin):
"""
Миксин для отслеживания просмотров страниц.
Добавляет трекинг при вызове view.
"""
def dispatch(self, request, *args, **kwargs):
# Отслеживаем просмотр перед обработкой запроса
track_page_view(request)
return super().dispatch(request, *args, **kwargs)
class MenuContextMixin(ContextMixin):
"""
Миксин для добавления меню в контекст.
"""
def get_context_data(self, **kwargs: Any) -> Dict[str, Any]:
context = super().get_context_data(**kwargs)
# Основное меню (всегда)
main_menu = [
# {'title': "Главная", 'url_name': 'home'},
{
'title': "Разработки",
'url_name': None,
'children': [
{'title': "Кейсы", 'url_name': 'solution'},
{'title': "Статьи", 'url_name': 'blog'},
]
},
{'title': "Отзывы", 'url_name': 'recall'},
{'title': "О нас", 'url_name': 'about'},
]
# Пользовательское меню (зависит от статуса)
if self.request.user.is_authenticated:
user_menu = [
{
'title': "Профиль",
'url_name': None,
'children': [
{'title': "Профиль", 'url_name': 'profile'},
{'title': "Выйти", 'url_name': 'logout'},
]
}
]
else:
user_menu = [
{
'title': "Войти",
'url_name': None,
'children': [
{'title': "Войти", 'url_name': 'login'},
{'title': "Регистрация", 'url_name': 'register'},
]
}
]
context['main_menu'] = main_menu
context['user_menu'] = user_menu
return context
class BreadcrumbMixin(ContextMixin):
"""
Миксин для добавления хлебных крошек в контекст.
В дочерних классах нужно определить метод get_breadcrumbs().
"""
breadcrumbs = None
def get_breadcrumbs(self):
"""
Должен возвращать список словарей:
[{'title': 'Название', 'url_name': 'url_name', 'url_args': [...], 'url_kwargs': {...}}, ...]
Последний элемент без url_name (текущая страница).
"""
if self.breadcrumbs is not None:
return self.breadcrumbs
return []
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['breadcrumbs'] = self.get_breadcrumbs()
return context