Django模板(请用Django2.0版本完成)
阅读原文时间:2023年08月20日阅读:1

(1)

很简单的,就直接右键learn,新建文件夹,完成后,继续右键templates,创建文档,后缀名为html就好。

(2)在home.html中写内容

欢迎光临

欢迎光临 芬芬笔迹

同样的,要保存哦

(3)改一下views.py文件

把先前的index函数注释掉,再重新写一个index函数

代码:

def index(request):

return render(request,'home.html')

注:以上render起的就是一个封装的作用

保存哦!

(4)改blog/urls.py

增加一个Path,将视图函数对应到网址

我这里用的是django3.0版本,先来一个错误示范:

以上在3.0版本是会运行错误的,经过我一个晚上加一个早上的抓耳挠腮、腰酸背痛,又秃了一大截的努力下,终于改对了!!!正确示范:

代码:

path('home/',learn_views.index,name='home'),

上面的错误太典型了!总结一下经验:首先,不能照本宣科,作为小白,我就是看着教材来弄的,结果,被带沟里!理解原理才是关键!其次,真的真的,你只要理解每个代码的前因后果,你自己是可以总结出一些规律,一些错误是可以自己解决的,上面那行代码,其实只要知道书写格式,这个完全可以从之前写过的习得,可我就是两眼一直只盯着那一行代码,知道今早才注意到上面几行代码。Path的第一个参数就是浏览器通过端口后,接着要访问的地址,后面你把它命名为home了,所以第一个参数也要加上,才能访问到,第二个参数,就是views.py里面的index了,就是一个路径名,这里之所以用learn_views,是因为

这一行代码,

保存!!!

(5)打开开发服务器并访问

(1)

这个和home.html的创建方法一样了,不做赘述,直接上图

代码:

Main

The Zen of Python


{% for item in entries1 %}

{{ item.title  }}  


{{ item.content  }}

{% endfor %}

(2)修改learn/views.py文件

添加代码:

from django.shortcuts import render_to_response

entries={'title':'1234','content':'5678'}

entries1=[{'title':'English','content':'Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren’t special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one– and preferably only one –obvious way to do it. Although that way may not be obvious at first unless you’re Dutch. Now is better than never. Although never is often better than right now. If the implementation is hard to explain, it’s a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea – let’s do more of those!'}         ,{'title':'中文','content':'优美胜于丑陋 明了胜于隐晦 简洁胜于复杂 复杂胜于混乱 扁平胜于嵌套 宽松胜于紧凑 可读性很重要 即便是特例,也不可违背这些规则 虽然现实往往不那么完美 但是不应该放过任何异常 除非你确定需要如此 如果存在多种可能,不要猜测 肯定有一种——通常也是唯一一种——最佳的解决方案 虽然这并不容易,因为你不是Python之父 , 动手比不动手要好 ,但不假思索就动手还不如不做, 如果你的方案很难懂,那肯定不是一个好方案 如果你的方案很好懂,那肯定是一个好方案, 命名空间非常有用,我们应当多加利用'}]

def list(request):

return render_to_response('list1.html',{'entries1':entries1})

这里着重理解一下:

render_to_response() 的第一个参数必须是要使用的模板名称。如果要给定第二个参数,那么该参数必须是为该模板创建 Context 时所使用的字典。如果不提供第二个参数,render_to_response() 使用一个空字典。

注意:render_to_response()这个在3.0版本以上是没有的!我又重新下载了2.0版本!

好,保存

(3)修改blog/blog/urls.py文件

代码:

path('list/',learn_views.list,name='list'),

(4)打开浏览器,并在浏览器地址栏输入:http://127.0.0.1:8002/list/

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器