python - 我无法将 CSS 文件链接到 Django 元素中的 HTML 文件

标签 python html css django

HTML 文件运行良好。但它没有与 CSS 链接,我在 CSS 中所做的根本不起作用。

HTML 页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TheWebPub</title>
    <link rel="stylesheet" href="stylepage.css">
</head>
<body>
    {% if name %}
    <h1 class='title'>Hello {{name}}. </h1>
    {% else %}
    <h1>Hello world.</h1>
    {% endif %}

    <p>Thank you for being here in my website, it's my first one. I'm creating this website with django/python.</p>
</body>
</html>

一切似乎都很好。这是我的 django 元素中的views.py 文件

from django.shortcuts import render
from django.http import request

# Create your views here.

def say_hello(request):
    return render(request, 'index.html', {'name':'Adryan'})

最佳答案

您无法传递对 templates 目录中文件的引用,实际上浏览器无法访问此文件:模板由网络服务器打开,然后呈现,结果通常是作为响应传递,就像这里的情况一样。

处理静态(或媒体)文件的方法是将它们存储在与 manage.py 文件同一级别的 static/ 根目录中。在 DEBUG = True 模式下,您可以通过将静态(和媒体)文件添加到 root urls.py 中,让 Django 提供静态(和媒体)文件:

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # the rest of your URLconf goes here …
] + <b>static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)</b>

然后在模板中我们传递对此文件的引用:

{% load static %}
<link rel="stylesheet" href="<b>{% static 'stylepage.css' %}</b>">

在生产中,您必须配置网络服务器,例如 nginx 或 apache 来提供静态文件。

有关详细信息,请参阅How to manage static files section of the documentation .

关于python - 我无法将 CSS 文件链接到 Django 元素中的 HTML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76988049/

相关文章:

python - BeautifulSoup 删除标签属性和文本内容

javascript - 通过单击 href url 加载新页面时不会调用 JavaScript 中的函数

javascript - 我们可以改变Json数据的Key值吗?

angular - 如何让图片留在容器内不溢出

python - Pyparsing infixNotation 为解析树 : Only one operator ending up in tree?

python - . argparse 参数和变量名称中的(点)

python - 关于定时事件的MUD(游戏)设计概念题

html - 圆形复选框在移动设备上无法正常工作

javascript - 如何在JavaScript中传输 'devicemotion'属性?

html - AngularJs 验证 CSS 错误