Django的MTV模式和模板01
本帖最后由 A913830 于 2021-11-14 10:10 编辑Django网站开发的mtv模式: Model(模型), Template(模板)和View(视图)。它们看似与MVC设计模式不太一致,其实本质是相同的。但是Django的View和经典的View确实有非常大的不同。- Model:与经典MVC模式下的Model差不多。是数据模型并不是数据本身- Template:与经典MVC模式下的View一致。决定了用户界面的外观- Views:负责业务逻辑,并调用Model和Template。此外还有一个路由分发器Urls,将一个个URL的页面请求分发给不同的View处理,View再调用相应的Model和Template。Urls+Views合起来使用,与经典MVC下的Controller更像
创建 templates 目录并建立 login.html文件
<form action="/login" method="post">
<div>username:<input type="text" name="username" value="{{name}}"></div>
<div>password:<input type="password" name="password" value="{{password}}"></div>
<div><input type="submit" value="login"></div>
</form>
修改模板文件的路径
def login(request):
if request.method == 'GET':
from django.template import loader
t = loader.get_template('login.html')
html = t.render({'name':'utility','password':'123'})
return HttpResponse(html)
def login(request):
if request.method == 'GET':
return render(request,'login.html',{'name':'bulletin'})
<p>{{s}}</p>
<p>{{lst}}</p>
<p>{{mydic}}</p>
<p>{{lst.0}}</p>
<p>{{mydic.name}}</p>
def test(request):
s = 'hello world!'
lst = ['A','B','C']
mydic = {'name':'utility','gender':'male'}
dic = {'s':s,'lst':lst,'mydic':mydic}
return render(request,'test.html',dic)
本帖最后由 A913830 于 2021-11-15 14:31 编辑
<form action="login" method="post">
<div>username:<input type="text" name="username" value="{{name}}"></div>
<div>password<input type="password" name="password" value="{{password}}"></div>
<div><input type="submit" value="login"></div>
</form>
def login(request):
if request.method == 'GET':
return render(request,'login.html',{'name':'bulletin'})
本帖最后由 A913830 于 2021-11-14 10:30 编辑
A913830 发表于 2021-11-13 21:09
{{s}}
{{lst}}
{{mydic}}
request.META['REMOTE_ADDR']
locals:the local scope 局部范围
def fx(a,b):
c = 300
print(locals())
fx(100,200)
{'a': 100, 'b': 200, 'c': 300}
def mytemp_view(request):
s = 'utility'
return render(request,'mytemp.html',locals()) <form action="./" method="post">
<input type="text" name="x" value="{{x}}">
<select id="" name="op">
<option value="add">+</option>
<option value="sub" {% if op == 'sub' %}selected{% endif %}>-</option>
</select>
<input type="text" name="y" value="{{y}}"> = <span>{{ret}}</span>
<div><input type="submit" value="calc"></div>
</form>
def calc(request):
if request.method == 'GET':
return render(request,'calc.html',locals())
elif request.method == 'POST':
if request.POST['x'] == '':
print('>>>>>>>>>')
x = int(request.POST.get('x','10'))
y = int(request.POST.get('y','20'))
op = request.POST.get('op')
if op == 'add':
ret = x+y
elif op == 'sub':
ret = x-y
return render(request,'calc.html',locals())
本帖最后由 A913830 于 2021-11-14 14:33 编辑
<div>
<h2>s = {{s|upper}}</h2>
<h2>s = {{s|safe}}</h2>
<h2>n+2 = {{n|add:2}}</h2>
</div>
def filter_view(request):
s = ' <i>hello world!</i> '
n = 100
return render(request,'filter.html',locals())
页:
[1]