`
喜欢蓝色的我
  • 浏览: 360096 次
  • 性别: Icon_minigender_2
  • 来自: 北京
社区版块
存档分类
最新评论

django学习知识点汇总(templates)

阅读更多

问题1:项目中存在多个app,每个app包括相同的名称的html文件,在页面显示是,访问url会产出模板不是真正想访问的模板

 

模板一般放在app下的templates中,Django会自动去这个文件夹中找。但 假如我们每个app的templates中都有一个 index.html,当我们在views.py中使用的时候,直接写一个 render(request, 'index.html'),Django 能不能找到当前 app 的 templates 文件夹中的 index.html 文件夹呢?(答案是不一定能,有可能找错)

Django 模板查找机制: Django 查找模板的过程是在每个 app 的 templates 文件夹中找(而不只是当前 app 中的代码只在当前的 app 的 templates 文件夹中找)。各个 app 的 templates 形成一个文件夹列表,Django 遍历这个列表,一个个文件夹进行查找,当在某一个文件夹找到的时候就停止,所有的都遍历完了还找不到指定的模板的时候就是 Template Not Found (过程类似于Python找包)。这样设计有利当然也有弊,有利是的地方是一个app可以用另一个app的模板文件,弊是有可能会找错了。所以我们使用的时候在 templates 中建立一个 app 同名的文件夹,这样就好了。

这就需要把每个app中的 templates 文件夹中再建一个 app 的名称,仅和该app相关的模板放在 app/templates/app/ 目录下面,

文件目录

例子:learn/templates/learn/home.html

在learn的views.py 中

from django.shortcuts import render
def home(request):
    return render(request,'learn/home.html')

 

在url.py 中存在两个相同name url

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', calc_views.index, name='home'),
    url(r'^home/$',learn_views.home, name='home'),
    url(r'^add/$',calc_views.add ,name='add'),
    url(r'^new_add/(\d+)/(\d+)/$', calc_views.add2, name='add2'),
    url(r'^add/(\d+)/(\d+)/$', calc_views.old_add2_redirect),
    #url(r'^search/$','mysite.books.views.search')
]

 

访问:http://127.0.0.1:8000/home/

可以访问到learn/templates/learn/home.html

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

问题二:

通过设置显示页面的元素

views.py

# -*- coding: utf-8 -*-
from django.shortcuts import render


def home(request):
    #字符串显示
    #string = u"我在自强学堂学习Django,用它来建网站"
    #return render(request, 'learn/home.html', {'string': string})
    #list 显示
    #TotorialList = ["html","css","jquery","python","djano"]
    #return render(request,'learn/home.html',{'TotorialList':TotorialList})
    #显示字典内容
    #info_dict = {'site': u'自强','content':u'独立'}
    #return render(request,'learn/home.html',{'info_dict':info_dict})
    #在模板进行条件判断和for循环的详细操作
List = map(str,range(100))
    return render(request,'learn/home.html',{'List':List})

home.html

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title> welcome</title>
</head>
<body>
welcome learn km
<!--{{ string }}
{% for i in TotorialList %}
{{ i }}
{% endfor %}
-->
<!--
我是:{{info_dict.site }}{{info_dict.content}}
{% for key, value in info_dict.items %}
    {{ key }}: {{ value }}
{% endfor %}
-->
{% for item in List %}
{{ item }}{% if not forloop.last %},{% endif %}
{% endfor %}

<a href="{{ request.path }}?{{ request.GET.urlencode }}&delete=1">当前网址加参数 delete</a>
</body>
</html>

 

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

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics