django加载css/js和图片等静态文件 (本地处理)

一、目录结构: 

整个目录结构是这样的:

mysite 

 

| —— manage.py 

 

| —— mysite 

 

| —— | —— settings 

 

| —— | —— … 

 

| —— blog 

 

| —— |——  ...

 

| —— | —— templates 

 

| —— | —— | ——  index.html

 

| —— | —— | ——  static 

 

| —— | —— | —— | —— css 

 

| —— | —— | —— |—— images

注意,文件夹结构比较复杂。 

 

在项目文件夹下有一个templates文件夹,不过这个文件夹暂时没什么用,可以不用管(我也不知道为什么要有这么个文件夹)。 

 

应用文件夹结构是这样的:

“blog/templates/index.html”; 

 

“blog/templates/static/images”; 

 

“blog/templates/static/CSS”;

二、设置templates和静态路径

在settings.py中设置templates路径

TEMPLATES = [

    {

        'BACKEND': 'django.template.backends.django.DjangoTemplates',

        'DIRS': [

            os.path.join(BASE_DIR, 'blog/templates').replace('\\', '/'),

        ],

        ...

     }

]

 

在settings.py文件的最后加上以下内容:

STATIC_ROOT = os.path.join(BASE_DIR, 'blog/templates/static').replace('\\', '/')

STATICFILES_DIRS = (

    ('css', os.path.join(STATIC_ROOT, 'css').replace('\\', '/')),

    ('images', os.path.join(STATIC_ROOT, 'images').replace('\\', '/')),

    ('js',os.path.join(STATIC_ROOT,'js').replace('\\', '/'))

)

 

三、修改urls.py文件 

 

在urls.py开头加上一句:

from django.contrib.staticfiles.urls import staticfiles_urlpatterns

 

在urls.py的最后加上以下内容:

#设置静态文件路径

urlpatterns += staticfiles_urlpatterns()

 

四、修改html文件 

 

index.html文件相关内容如下:

<html lang="en">

<head>

    <link href="/static/css/style.css" rel="stylesheet" type="text/css" />

    <title>Hometitle>

head>

<body>

    <a href="https://www.baidu.com/>

        /static/images/logo.png" alt="logo"/>

    a>

body>

html>

 

 

你可能感兴趣的:(python)