变量的过滤器(filter)的使用
过滤器:upper, lower, first, capfirst
在 views.py 中修改
from Django.shortcuts import render
# Create your views here.
def index(req):
s="hello"
return render(req,"index.html",{"obj":s })
在 index.html中修改
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>Template</h1>
{{ obj|upper }}
{{ obj|lower }}
{{ obj|first }}
{{ obj|capfirst }}
</body>
</html>
过滤器:add
在 views.py 中修改
from djanGo.shortcuts import render
# Create your views here.
def index(req):
s6=1
return render(req,"index.html",{"obj":s6 })
在 index.html中修改
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>Template</h1>
{{ obj|add:5 }}
</body>
</html>
过滤器: default
如果值是False,就替换成设置的默认值,否则就是用本来的值
在 views.py 中修改
from django.shortcuts import render
import datetime
# Create your views here.
def index(req):
...
s7=[]
return render(req,"index.html",{"obj":s7 })
在 index.html中修改
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>Template</h1>
{{ obj|default:"空" }}
</body>
</html>
过滤器: autoescape
在 views.py 中修改
from django.shortcuts import render
import datetime
# Create your views here.
def index(req):
...
s8="<a href='#'>跳转</a>"
return render(req,"index.html",{"obj":s8 })
在 index.html中修改
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>Template</h1>
{% autoescape off%}
{{ obj }}
{% endautoescape %}
</body>
</html>
或者
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>Template</h1>
{{ obj | safe}}
</body>
</html>
csrf_token标签
用于生成csrf_token的标签,用于防治跨站攻击验证。注意如果你在view的index里用的是render_to_response方法,不会生效其实,这里是会生成一个input标签,和其他表单标签一起提交给后台的。
在 urls.py 中修改
from django.contrib import admin
from django.urls import path
from app01 import views
urlpatterns = [
....
path('login/', views.login),
]
在 views.py 中修改
....
def login(req):
if req.method=="POST":
return HttpResponse("ok")
return render(req, "login.html")
添加一个login.html 页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<fORM action="/login/" method="post">
<input type="text" name="user">
<input type="text" name="pwd">
<input type="submit" value="submit">
{% csrf_token %}
</form>
</body>
</html>