标签:fonts 表单 修改 根据 site mime类型 重用 extends info
由startproject命令生成的settings.py定义关于模板的值:
DIRS=[os.path.join(BASE_DIR,"templates")]
loader.get_template(template_name),返回一个Template对象
Template对象的render(RequestContext)方法,使用context渲染模板
from django.template import loader, RequestContext
from django.http import HttpResponse
def index(request):
tem = loader.get_template(‘ectest/index.html‘)
context = RequestContext(request, {})
return HttpResponse(tem.render(context))
from django.shortcuts import render
def index(request):
return render(request, ‘ectest/index.html‘)
{{ variable }}
from django.db import models
class HeroInfo(models.Model):
...
def showName(self):
return self.hname
from django.shortcuts import render
from models import *
def index(request):
hero = HeroInfo(hname=‘abc‘)
context = {‘hero‘: hero}
return render(request, ‘ectest/detail.html‘, context)
{{hero.showName}}
注意:不能传递参数
{ %for ... in ...%}
循环逻辑
{{forloop.counter}}表示当前是第几次循环
{ %empty%}
给出的列表为空或列表不存在时,执行此处
{ %endfor%}
{ %if ...%}
逻辑1
{ %elif ...%}
逻辑2
{ %else%}
逻辑3
{ %endif%}
{ %include "foo/bar.html" % }
{ % url ‘name‘ p1 p2 %}
{ % csrf_token %}
# 可以在if标签中使用过滤器结合运算符
if list1|length > 1
# 过滤器能够被“串联”,构成过滤器链
name|lower|upper
# 过滤器可以传递参数,参数使用引号包起来
list|join:", "
# default:如果一个变量没有被提供,或者值为false或空,则使用默认值,否则使用变量的值
value|default:"什么也没有"
# date:根据给定格式对一个date变量格式化
value|date:‘Y-m-d‘
{#...#}
# comment标签
{ % comment % }
多行注释
{ % endcomment % }
查询所有英雄信息显示出来,要求奇数行显示为红色,偶数行显示为蓝色
{ %block block_name%}
这里可以定义默认值
如果不定义默认值,则表示空字符串
{ %endblock%}
{ % extends "base.html" %}
{ %block block_name%}
实际填充内容
{ %endblock%}
{ % block block_name %}
区域内容
{ % endblock block_name %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{% block title %}{% endblock %} 水果超市</title>
</head>
<body>
<h1>top--{{logo}}</h1>
<hr/>
{% block content %}{% endblock %}
<hr/>
bottom
</body>
</html>
{% extends ‘ectest/base.html‘ %}
{% block title %}商品{% endblock title %}
{% block content %}
<table border="1">
<tr>
<td height="300">
{% block left %}推荐商品{% endblock left %}
</td>
<td width="300" align="center">
{% block goods_content %}
{% endblock %}
</td>
</tr>
</table>
{% endblock content%}
{% extends ‘ectest/base.html‘%}
{% block title %}用户中心{% endblock %}
{% block content %}
<table border="1">
<tr>
<td height="300">
{% block left %} 用户导航{% endblock left %}
</td>
<td width="300" align="center">
{% block user_content %}
{% endblock %}
</td>
</tr>
</table>
{% endblock content%}
{% extends ‘ectest/base.html‘ %}
{% block content %}
首页内容
{% endblock content%}
3.为具体页面创建模板,继承自分支模板
{%extends ‘ectest/base_goods.html‘%}
{%block goods_content%}
商品正文列表
{%endblock goods_content%}
{%extends ‘ectest/base_user.html‘%}
{%block user_content%}
用户密码修改
{%endblock user_content%}
4.视图调用具体页面,并传递模板中需要的数据
logo=‘welcome to igeek‘
def index(request):
return render(request, ‘ectest/index.html‘, {‘logo‘: logo})
def goodslist(request):
return render(request, ‘ectest/goodslist.html‘, {‘logo‘: logo})
def userpwd(request):
return render(request, ‘ectest/userpwd.html‘, {‘logo‘: logo})
from django.conf.urls import url
from . import views
urlpatterns = [
url(r‘^$‘, views.index, name=‘index‘),
url(r‘^list/$‘, views.goodslist, name=‘list‘),
url(r‘^pwd/$‘, views.userpwd, name=‘pwd‘),
]
视图代码: def index(request): return render(request, ‘ectest/index2.html‘, { ‘t1‘: ‘<h1>hello</h1>‘ }) 模板代码: {{t1}}
< 会转换为< > 会转换为> ‘ (单引号) 会转换为' " (双引号)会转换为 " & 会转换为 &
{{t1|escape}}
{{ data|safe }}
{ % autoescape off %}
{{ body }}
{ % endautoescape %}
{ { data|default:"<b>123</b>" }} # 应写为: { { data|default:"<b>123</b>" }}
def csrf1(request): return render(request,‘booktest/csrf1.html‘) def csrf2(request): uname=request.POST[‘uname‘] return render(request,‘booktest/csrf2.html‘,{‘uname‘:uname})
url(r‘^csrf1/$‘, views.csrf1), url(r‘^csrf2/$‘, views.csrf2),
<html> <head> <title>Title</title> </head> <body> <form method="post" action="/crsf2/"> <input name="uname"><br> <input type="submit" value="提交"/> </form> </body> </html>
<html>
<head>
<title>Title</title>
</head>
<body>
{{ uname }}
</body>
</html>
<form> {% csrf_token %} ... </form>
from django.views.decorators.csrf import csrf_exempt @csrf_exempt def csrf2(request): uname=request.POST[‘uname‘] return render(request,‘booktest/csrf2.html‘,{‘uname‘:uname})
<input type=‘hidden‘ name=‘csrfmiddlewaretoken‘ value=‘nGjAB3Md9ZSb4NmG1sXDolPmh3bR2g59‘ />
# -*- coding: utf-8 -*- from django.http import HttpResponse, HttpResponseRedirect from PIL import Image, ImageFont, ImageDraw import random import cStringIO def verifycode(request): # 图像的背景色 bgcolor = (random.randrange(20, 100), random.randrange(20, 100), 255) # 图像宽 width = 100 # 图像高 heigh = 25 # 创建图像对象 img = Image.new(‘RGB‘, (width, heigh), bgcolor) # 创建可以图像对象绘图的Draw对象 draw = ImageDraw.Draw(img) # 在图像上随机100个坐标上绘制画点 for i in range(0, 100): xy = (random.randrange(0, width), random.randrange(0, heigh)) fill = (random.randrange(0, 255), 255, random.randrange(0, 255)) draw.point(xy, fill=fill) # 定义验证码的备选值 str1 = ‘ABCD123EFGHIJK456LMNOPQRS789TUVWXYZ0‘ # 在备选值中随机选取4个值作为验证码 random_str = ‘‘ for i in range(4): random_str += str1[random.randrange(len(str1))] # 构造字体对象 font = ImageFont.truetype(‘C:\Windows\Fonts\Arial.ttf‘, 23) # 构造字体颜色 fontcolor = (255, random.randrange(0, 255), random.randrange(0, 255)) # 绘制4个值作为验证码 for t in range(4): draw.text((25 * t + 5, 2), random_str[t], font=font, fill=fontcolor) # 释放Draw对象 del draw # 将验证码存入session,用于做进一步验证 request.session[‘verifycode‘] = random_str # 将图片对象以类型为png保存到内存中 buf = cStringIO.StringIO() img.save(buf, ‘png‘) # 将内存中的图片数据返回给客户端,MIME类型为图片png return HttpResponse(buf.getvalue(), ‘image/png‘)
from django.conf.urls import url from . import views, viewsUtil urlpatterns = [ url(r‘verifycode/$‘, viewsUtil.verifycode, name=‘verifycode‘), ]
from django.shortcuts import render def index(request): return render(request, ‘booktest/index1.html‘)
from django.conf.urls import url from . import views, viewsUtil urlpatterns = [ url(r‘^index/$‘, viewsUtil.index, name=‘index1‘), ]
<img id=‘verifycode‘ src="/verifycode/" alt="CheckCode">
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <script type="text/javascript" src="/static/jquery-3.3.1.min.js"></script> <script type="text/javascript"> $(function () { $(‘#verifycodeChange‘).css(‘cursor‘, ‘pointer‘).click(function () { $(‘#verifycode‘).attr(‘src‘, $(‘#verifycode‘).attr(‘src‘)+1) }); }); </script> <img id=‘verifycode‘ src="/verifycode/?" alt="CheckCode"> <span id="verifycodeChange">看不清,换一个</span>
<form method="post" action="/verifycodeValid/"> {% csrf_token %} <input type="text" name="vc"> <img id=‘verifycode‘ src="/verifycode/?" alt="CheckCode"> <span id="verifycodeChange">看不清,换一个</span> <br> <input type="submit" value="提交"> </form>
from django.http import HttpResponse, HttpResponseRedirect def verifycodeValid(request): vc = request.POST[‘vc‘] if vc.upper() == request.session[‘verifycode‘]: return HttpResponse(‘登录成功‘) else: return HttpResponseRedirect(reverse(‘booktest:index1‘))
from django.conf.urls import url from . import views, viewsUtil urlpatterns = [ url(r‘verifycodeValid/$‘, viewsUtil.verifycodeValid, name=‘verifycodeValid‘) ]
标签:fonts 表单 修改 根据 site mime类型 重用 extends info
原文地址:https://www.cnblogs.com/Mint-diary/p/9776142.html