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/