Проблема с переключением между темами
Я столкнулся с проблемой установки пользовательской темы в моем проекте Django, использующем версию 4.2.13 и Python версии 3.9.7. В админке по умолчанию есть значок луны для переключения тем (т.е. между светлой, темной и авто). Я хочу добавить серую тему в качестве темы по умолчанию с новой иконкой. Таким образом, сейчас есть 4 значка для тем - Grey, Light, Dark & Auto. Для реализации этого я добавил новую иконку для темы Grey, и теперь эта иконка не видна в админ-панели (отображаются только 3 по умолчанию), а переключение между темами не работает. Ниже приведены скриншоты кода для установки тем с соответствующими иконками.
Обратите внимание, что мой товарищ по команде работал над Django 5.0, чтобы сделать коммиты своего предыдущего проекта в Github. Мы хотели проверить, что может произойти с одной и той же функциональностью, если члены команды работают на разных версиях, поскольку мы предполагаем, что Git по сути хранит все файлы как базовые текстовые файлы с контролем версий. Я не уверен, имеет ли это отношение к моей проблеме.
Добрая помощь.
1.Скриншот 1 - js файл для переключения и добавления иконки (admin_script.js)
document.addEventListener("DOMContentLoaded", function() {
const themeSwitcher = document.getElementById("theme-switcher");
// Function to set the theme in the body and save it in a cookie
function setTheme(theme) {
document.body.classList.remove("dark-theme", "grey-theme", "light-theme");
document.body.classList.add(theme);
document.cookie = `theme=${theme}; path=/;`;
// Update button text based on the current theme
if (theme === "light-theme") {
themeSwitcher.textContent = "Switch to Dark Theme";
} else if (theme === "grey-theme") {
themeSwitcher.textContent = "Switch to Light Theme";
} else {
themeSwitcher.textContent = "Switch to Grey Theme";
}
}
// Function to get the theme from cookies
function getTheme() {
const name = 'theme=';
const decodedCookie = decodeURIComponent(document.cookie);
const cookies = decodedCookie.split(';');
for(let i = 0; i < cookies.length; i++) {
let cookie = cookies[i].trim();
if (cookie.indexOf(name) == 0) {
return cookie.substring(name.length, cookie.length);
}
}
return null;
}
// Apply the stored theme on page load
const currentTheme = getTheme();
if (currentTheme) {
setTheme(currentTheme);
} else {
setTheme('grey-theme'); // Default to light theme if no theme is set
}
// Event listener for the theme switch button
themeSwitcher.addEventListener("click", function() {
let newTheme;
if (document.body.classList.contains("light-theme")) {
newTheme = "dark-theme";
} else if (document.body.classList.contains("grey-theme")) {
newTheme = "light-theme";
} else {
newTheme = "grey-theme";
}
setTheme(newTheme);
});
});
2.Скриншот 2 - код для добавления новой иконки переключения (color_theme_toggle.html)
{% load i18n %}
<button class="theme-toggle">
<div class="visually-hidden theme-label-when-auto">{% translate 'Toggle theme (current theme: auto)' %}</div>
<div class="visually-hidden theme-label-when-light">{% translate 'Toggle theme (current theme: light)' %}</div>
<div class="visually-hidden theme-label-when-dark">{% translate 'Toggle theme (current theme: dark)' %}</div>
<div class="visually-hidden theme-label-when-grey">{% translate 'Toggle theme (current theme: grey)' %}</div>
<svg aria-hidden="true" class="theme-icon-when-auto">
<use xlink:href="#icon-auto" />
</svg>
<svg aria-hidden="true" class="theme-icon-when-dark">
<use xlink:href="#icon-moon" />
</svg>
<svg aria-hidden="true" class="theme-icon-when-light">
<use xlink:href="#icon-sun" />
</svg>
<svg aria-hidden="true" class="theme-icon-when-grey">
<use xlink:href="#icon-grey" />
</svg>
</button>
3.Скриншот 3 - Добавление svg-файла для новой иконки (new.svg)
<svg xmlns="http://www.w3.org/2000/svg" style="display:none">
<symbol id="icon-grey" viewBox="0 0 24 24">
<circle cx="12" cy="12" r="10" fill="#808080"/>
</symbol>
</svg>
4.Скриншот 4 - Расширение базового сайта и добавление css и js файлов (base_site.html)
{% extends "admin/base_site.html" %}
{% load static %}
{% block extrahead %}
{{ block.super }}
<link rel="stylesheet" type="text/css" href="{% static 'admin/css/custom_admin.css' %}">
{% endblock %}
{% block extra_js %}
{{ block.super }}
<script src="{% static 'js/theme.js' %}"></script>
{% endblock %}
В моем проекте Django я хочу добавить новую иконку для серой темы и переключаться между ними с существующими темами по умолчанию.Поэтому я хочу добавить одну иконку для серой темы и переключаться между темами.