Skip to main content
 首页 » 编程设计

python之如何在 Django 中添加我自己的 html 模板

2025年05月04日28qlqwjy

我是django的新手,我的问题是如何给css和js链接

{% load staticfiles %} 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
  <html xmlns="http://www.w3.org/1999/xhtml"> 
     <head> 
     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
     <title>Welcome</title>    
     <link href="css/templatemo_style.css" rel="stylesheet" type="text/css" /> 
     <link rel="stylesheet" type="text/css" href="{% static "css/templatemo_style.css" %}" /> 
     <script type="text/javascript" src="js/jquery.min.js"></script> 

css 和 js 不是从实际路径加载的,不知道如何在 html 中使用静态文件夹的实际路径 我正在尝试使用

import os 
#DIRNAME = os.path.abspath(os.path.dirname(__file__)) 
DIRNAME = os.path.dirname(__file__) 

但它给了我错误的路径

我提供一个简短的描述:

TEMPLATE_DIRS = ( 
os.path.join(DIRNAME, 'static/'), 
} 

我的网址是

http://127.0.0.1:8000/blog/home/ 

显示错误

Template-loader postmortem 
 
Django tried loading these templates, in this order: 
 
Using loader django.template.loaders.filesystem.Loader: 
    D:\Eclipse_JEE_new_workspace\testing\testing\static\index.html (File does not exist) 
Using loader django.template.loaders.app_directories.Loader: 
    C:\Python27\lib\site-packages\django\contrib\auth\templates\index.html (File does not exist) 
    C:\Python27\lib\site-packages\django\contrib\admin\templates\index.html (File does not exist) 

它显示:

D:\Eclipse_JEE_new_workspace\testing\testing\static\index.html 

但实际

如果我将静态文件夹移动到测试文件夹中,它就是一个没有 css 和 js 链接的 html 页面

D:\Eclipse_JEE_new_workspace\testing\static\index.html 

抱歉,现在的情况是:

当页面加载 css 链接给我一个错误 404 但相同的位置 index.html 页面加载
如何包含css/js?
在目前的情况下,我正在使用
{% include 'header.html' %}
包含在 index.html 中

请您参考如下方法:

模板文件应该放在 templates 文件夹中。 DIRNAME 具有指向 settings.py 的路径。

应该是这样的:

DIRNAME = os.path.join(os.path.dirname(__file__), '..') 
TEMPLATE_DIRS = ( 
    os.path.join(DIRNAME, 'templates/'), 
} 

并确保您的 index.html 位于 templates 文件夹中。