【发布时间】:2021-11-02 17:20:26
【问题描述】:
所以我正在开发一个 Django 网站,并希望该网站的访问者点击他们想要的主题。我可以使用纯 Html/css 和 Javascipt 来做到这一点,但现在我在 Django 中移动所有内容,它无法正常工作。我想也许它是我的路径设置。首先是我的 index.html 中的代码
<h5 style="text-align: center;line-height: 0;">Personalize Theme</h5>
{% load static %}
<script type="text/javascript" src="../../static/pythonicThinking/script.js"></script>
<div id="theme-options-wrapper">
<div data-mode="light" id="light-mode" class="theme-dot" ></div>
<div data-mode="blue" id="blue-mode" class="theme-dot"></div>
<div data-mode="green" id="green-mode" class="theme-dot"></div>
<div data-mode="purple" id="purple-mode" class="theme-dot"></div>
</div>
<p id="settings-note">*Theme settings will be saved for<br>your next visit</p>
</div>
javacript 文件
console.log('Its working')
let theme = localStorage.getItem('theme')
if(theme == null){
setTheme('light')
}else{
setTheme(theme)
}
let themeDots = document.getElementsByClassName('theme-dot')
for (var i=0; themeDots.length > i; i++){
themeDots[i].addEventListener('click', function(){
let mode = this.dataset.mode
console.log('Option clicked:', mode)
setTheme(mode)
})
}
function setTheme(mode){
if(mode == 'light'){
document.getElementById('theme-style').href = 'default.css'
}
if(mode == 'blue'){
document.getElementById('theme-style').href = 'blue.css'
}
if(mode == 'green'){
document.getElementById('theme-style').href = 'green.css'
}
if(mode == 'purple'){
document.getElementById('theme-style').href = 'purple.css'
}
localStorage.setItem('theme', mode)
}
setting.py 文件
# Static files (CSS, JavaScript, Images)
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
urls.py 文件 从 django.views.generic 导入重定向视图
urlpatterns = [
path('admin/', admin.site.urls),
path('pythonicthinking/', include('pythonicthinking.urls')),
]
urlpatterns += [
path('', RedirectView.as_view(url='pythonicthinking/', permanent=True)),
]
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
views.py 文件 from django.shortcuts 导入渲染
def home(request):
return render(request, 'pythonicthinking/index.html')
我的默认 css 正在工作,但是当我尝试单击按钮进行更改时,我收到此错误
Refused to apply style from 'http://127.0.0.1:8000/pythonicthinking/purple.css' because its
MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is
enabled
【问题讨论】:
-
显示导入静态CSS文件的代码(模板)。
-
加载静态js的正确方法是
src="{% static 'pythonicThinking/script.js' %}" -
也许这就是我搞砸的地方,你的意思是显示整个 index.html 页面,我认为我正在导入的地方以及每当我尝试以这种方式加载它时 src="{% static ' pythonicThinking/script.js' %}" 我得到未解决的模板参考
-
分享这些错误
标签: python css django web django-views