Python学习---Django重点之静态资源配置

[官网静态文件介绍] https://docs.djangoproject.com/en/1.10/howto/static-files/

wpsBA2A.tmp

# settings.py 配置静态资源文件

# STATIC_URL别名设置,默认会去STATICFILES_DIRS下找路径,这里helloworld代指statics

# 好处就是无论后台怎么更改路径,前面任然只需要调用helloworld即可

STATIC_URL = '/helloworld/'

<script src="/helloworld/jquery-3.2.1.js'"></script> # 利用helloworld映射下面的statics
      STATICFILES_DIRS = (os.path.join(BASE_DIR, "statics"),)   # 这里是个数组

----------------------------------------------------------------------------------------------------------------------------------

settigs.py:增加STATICFILES_DIRS静态资源路径配置,名称为创建的文件夹名称

'DIRS': [os.path.join(BASE_DIR, 'templates')],  # 设置templates的路径为Django以前版本
# 'DIRS': [],      # 注释掉该行,此为Django 2.0.1最新版本
# 'django.middleware.csrf.CsrfViewMiddleware',
         ...省略默认配置
STATIC_URL = '/static/'
TEMPLATE_DIRS = (os.path.join(BASE_DIR,  'templates'),)  # 原配置
# 静态资源文件
STATICFILES_DIRS = (os.path.join(BASE_DIR, "statics"),)   # 现添加的配置,这里是元组,注意逗号
#  我们一般只用 STATIC_URL,但STATIC_URL会按着你的STATICFILES_DIRS去找

templates/static_index.html

<!DOCTYPE html>
<html lang="en">
<head> <meta charset="UTF-8"></head>
<body>
    <p id="h1">数据展示</p>
    {# {% load staticfiles %}#}        {# 这种静态加载也是可以的 #}
    {% load static   %}
<!--第一种方法-->
<script src="{% static '/jquery-3.2.1.js' %}"></script>
 {# setting.py里面已经配置了静态资源加载statics,所以这里直接写/XXX.js #}
<!--第二种方法【推荐使用,简单,不需要上面的{% load %}】-->
<script src="/static/jquery-3.2.1.js"></script>
<script>
    $("p").css("color","red")
</script>

</body>
</html>

mysite2/urls.py

from django.contrib import admin
from django.urls import path
from blog import views

urlpatterns = [
       path(r'static_index/',  views.static_index),  # 将路径名跟函数进行映射
]

views.py

from django.shortcuts import render
def static_index(request):
    return render(request, "static_index.html")
    # 这里第一个参数必须是rquest, 第二个参数是我们页面HTML的名称
    # 这里直接写HTML名称是因为Django将参数封装再来settings.py文件内

页面显示:

image

简单问题记录

问题一: You called this URL via POST, but the URL doesn't end in a slash[斜线]

            -->意思是POST请求未结束,少一个斜线

image

image

 

[静态配置问题解决] https://www.cnblogs.com/Andy963/p/Django.html

猜你喜欢

转载自www.cnblogs.com/ftl1012/p/9398087.html