Django 加载css、js及静态图片

来自CloudWiki
跳转至: 导航搜索

这篇文章介绍的内容是关于Django如何加载css和js文件以及静态图片,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下

创建文件夹

首先我们应该创立一个文件夹名字为static 该文件夹用于用于保存和存储css,js和图片文件 我们可以在static里面创建文件css,images,和js文件夹,用于存储三类文件,文件夹名字不固定,前面这样取是为了方便记忆。

Big1-28.png

├── static
│   ├── css
│   │   ├── index0.css
├── templates
│   ├── test.html


修改配置文件

创建文件夹后再settings里面写入代码

STATIC_URL = '/static/'
STATICFILES_DIRS=[

        os.path.join(BASE_DIR,'static'),

]

修改html文件

然后要在使用样式的页面头部加载static

<!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>
<title>第一个HTML页面</title>
{% load static %}
<link type="text/css" rel="stylesheet" href="{% static "css/index0.css" %}"/>
</head><body>
  <h2>这是第一个HTML页面</h2>
  <hr />        
  <p>我们现在在学习HTML+CSS+JavaScript,这是我们制作的第一个HTML页面。</p>
</body></html>


效果

Big1-29.png

相关文件

对应url文件

blog/urls.py:

from django.conf.urls import  url
from . import views
from . import search
urlpatterns = [
    # url(r'^api/list$', views.BlogView.as_view(), name='blog-list'),
    url(r'^api/$', views.hello),
    url(r'^search/$',search.search)

对应视图层文件

# 提交后的接收请求数据
def search(request):
    request.encoding='utf-8'   
    context          = "hello world"
    return render(request, 'test.html', context)


对应CSS文件

static/css/index0.css:

h2{ color:blue; text-align:center; } 

参考资料:

https://www.php.cn/js-tutorial-393710.html