【问题标题】:How to add multiple css file in django3 in a single html file?如何在单个html文件中在django3中添加多个css文件?
【发布时间】:2020-10-22 01:43:22
【问题描述】:

我在模板文件夹中有一个名为index.html 的html 文件,两个css 文件computer.cssmobile.css 都在静态文件夹中。如何在单个 index.html 文件中使用它们。

【问题讨论】:

    标签: html css python-3.x django


    【解决方案1】:

    只需像通常在 HTML 中那样添加它们。但是对于静态文件,您必须在 HTML 文件中包含 {% load static %},并且当您访问 css 文件的 URL 时,请以 django 的方式进行,如下所示:

    index.html

    {% load static %}
    <html>
    <head>
        <title>...</title>
        <link rel="stylesheet" href="{% static './path/to/css' %}">
        <link rel="stylesheet" href="{% static './path/to/another/css' %}">
    </rest of the code>...
    

    TL/DR:在生产中,像 CSS 这样的静态文件应该由像 nginx 这样的代理服务器处理。因此,如果您处于开发阶段,您的服务器可能无法解析静态文件夹的目录。为此,您可以在项目的 urls.py

    中手动添加以下代码
    from django.urls import re_path
    from django.views.static import serve
    from django.conf import settings
    
    urlpattern += [
      re_path(r'^static/(?:.*)$', serve, {'document_root': settings.STATIC_ROOT, })
    ]
    

    并在您的 settings.py

    中定义 STATIC_ROOT
    STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
    

    【讨论】:

      猜你喜欢
      • 2015-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多