Django(3)--访问静态资源和模板

时间:2022-12-14 11:28:00

初学Django,在访问模板和静态资源满脸泪。模板还好说,尤其是静态资源,简直无语了....

本人用的是python2.7,django1.8

IDE工具是pycharm3

我们的目录结构如下,添加了模板文件夹和静态资源文件夹

Django(3)--访问静态资源和模板

首先我们在blob的视图文件中定义index方法访问模板index.html文件,urls.py文件指向我们的方法,如图

Django(3)--访问静态资源和模板

我们定义的视图方法如下:

Django(3)--访问静态资源和模板

现在我们访问以下这个方法 http://localhost:8000/blob/发现访问出错,找不到模板,

Django(3)--访问静态资源和模板

因为我们没有配置模板的指向路径,打开setting.py文件,配置如下:

Django(3)--访问静态资源和模板

我们再次访问发现已经找到了模板,但是模板中的静态资源如图片等没有加载出来,如图:

Django(3)--访问静态资源和模板

现在我们就需要配置静态资源了,打开setting.py文件配置,加入下面代码

STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "common-static"),
]
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
另外在加入红线部分代码,启用静态文件

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['templates'],
'APP_DIRS': True,
'OPTIONS': dict(context_processors=[
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
<span style="color:#ff0000;"> 'django.core.context_processors.static',</span>
]),
},
]
修改index方法

def index(request):
return render_to_response('index.html',locals(),context_instance=RequestContext(request))
#return render_to_response('index.html')

最后在HTML文件中用{{ STATIC_URL }}获取静态文件相对路径,如图:

<img src="{{ STATIC_URL }}images/tm-easy-profile.jpg" class="img-responsive img-circle tm-border" alt="templatemo easy profile">
这是我们再访问一下页面:
 
Django(3)--访问静态资源和模板

终于成功了啊。。。。满脸泪。