十二、Django视图函数和模版相关

视图相关

HTTPRequest对象:
属性:path
函数:get_full_path()
HTTPResponse对象:
render()
render_to_response()
locals() :局部变量

redirect() 重定向

例子:用户登录成功后跳转

def login(request):
    ...
    # 判断登录成功后,跳转到index
    return render(request, "index.html")
    ...

在上述代码下,用户登录成功,后台直接渲染index页面给用户,不经过urls路由,url还是.../login/ 用户登录的url。
修改:

def login(request):
    ...
    # 判断登录成功后,跳转到index
    return redirect("/index/")
    ...

使用redirect ( ) 就可以经过urls路由跳转到index页面,经过index对应的视图函数

模版相关

1、参数

t = "hello world!"
name = "Tom"
return render(req, "index.html", {"str":t, "name":name, "request":request,})

上下文查询
<h1>{{ name }}{{ t }}</h1>
深度查询
a、句点符
<h1>{{ request.method }}</h1>
b、索引查询

names = ["Tom", "Hedi",]
return render(req, "index.html", {"names":names, "request":request,})
<h1>{{ names.0 }}</h1>
<h1>{{ names.1 }}</h1>

c、查询字典

s = {“name”:“Tom”, “age":20, "gender":"man"}
return render(req, "index.html", {"s":s, "request":request,})
<h1>{{ s.name }}</h1>
<h1>{{ s.age }}</h1>
<h1>{{ s.gender }}</h1>

d、查询对象属性

class Animal():
    def __init__(self, name, sex, age):
        self.name = name
		self.sex = sex
        self.age = age

def query(request):
    a = Animal("qe", "male", 10)
    return render(request, "index.html", {"animal":a})
<h1>{{ a.name }}</h1>
<h1>{{ a.sex }}</h1>

2、标签(tag)的使用

a、if

{% if a.age > 10 %}
	<h1>hello {{ a.name }}</h1>
{% endif %}
{% if a.age > 10 %}
	<h1>hello {{ a.name }}</h1>
	{% if a.age > 20 %}
		<h1>年龄大于20</h1>
	{% else %}
  	<h1>年龄大于10小于20</h1>
	{% endif %}
{% elif a.age > 5 %}
	<h1>{{ a.name }} 的年龄大于5小于10</h1>
{% else %}
	<h1>{{ a.name }} 的年龄小于5</h1>
{% endif %}

b、for

{% for n in names %}
	{{ n }}
{% endfor %}

索引:forloop.counter 、 forloop.counter0

{% for n in names %}
	<p>{{ forloop.counter }}:{{ n }}</p>
{% endfor %}

forloop.first

{% for n in names %}
	{% if forloop.first %}
  	<li class="first">
  {% else %}
    <li>
  {% endif %}
	{{ n }}
  </li>
{% endfor %}

empty

{% for n in names %}
	<p>{{ forloop.counter }}:{{ n }}</p>
{% empty %}
<p>无相关内容</p>
{% endfor %}

c、csrf_token标签

<form action="{% url "reg" %}" method="POST">
  {% csrf_token %}
    <p>姓名<input type="text" name="user"></p>
    <p>年龄<input type="text" name="age"></p>
    <p>爱好<input type="checkbox" name="hobby" value="1">篮球
            <input type="checkbox" name="hobby" value="2">足球
            <input type="checkbox" name="hobby" value="3">乒乓球
    </p>
    <p><input type="submit">提交</p>
</form>

csrf_token标签的作用: 在template渲染时django给模版发一个身份信息如下图,name=...,value=...,使form表单post提交时后台根据这个身份信息能认识这个提交。从而避免了静态文件一章中的csrf中间拦截。
页面源码:

csrf_token标签使form表单增加了一个hidden的input,持有后台给的name和value

d、其它标签

url、with、verbatim、load等

2、Fliter的使用(过滤器)

https://c.biancheng.net/view/7580.html

过滤器 使用说明。
length 获取变量的长度,适用于字符串和列表。
lower/upper 转换字符串为小写/大写形式。
first/last 获取变量的首个/末尾元素。
add:'n' 给变量值增加 n。
safe 默认不对变量内的字符串进行html转义。
cut 从给定的字符串中删除指定的值。
dictsort 获取字典列表,并返回按参数中给定键排序的列表。
join 用字符串连接列表,例如 Python 的 str.join(list)。
truncatewords 如果字符串字符多于指定的字符数量,那么会被截断。 截断的字符串将以可翻译的省略号序列(“...”)结尾。

使用例子:

<p>hello:{{value|length}}</p>  # 如果value=“Tom”,则过滤器结果为3.另外,value也可以是列表或字典
<p>hello:{{value|truncatewords:2}}</p> # value=Django is website,则过滤器结构为Django is ...

3、自定义过滤器

1、在app中创建templatetags模块

2、创建任意.py文件,如:my_tags.py

定义代码:

from django import template
from django.utils.safestring import mark_safe

register = template.Library() #register的名字是固定

@register.filter
def filter_multi(x,y):
    return x*y

3、使用

{% load my_tags %}

{{ a.age|filter_multi:2 }}

@register.filter #只能传一个参数
simple_tag可以传多个参数

4、simple_tag

@register.simpler_tag
def simple_tag_multi2(x,y,z):
    return x*y*z

{% simple_tag_multi2 3 8 2 %}
但simple_tag不能用在控制语句中,必须用@register.filter

4、继承

{% block %}

在html中添加block标签,让继承它的子模版可以修改内容

<body>
  ...
  {% block content %}
    <p>Welcome to base</p>
  {% endblock %}
  ...
</body>

让index.html继承base.html

{% extend "base.html" %}

{% block content %}
	{% for student in student_list %}
     <h2>学生{{ student }}</h2>
  {% endfor %}
{% endfor %}

在head中也可以写block

<head>
  ...
  {% block styles %}
  {% endblock %}
  ...
</head>
{% extend "base.html" %}

{% block styles %}
	<style>
    h2{
        color:red;
    }
  </style>

{% endblock %}

{% block content %}
	{% for student in student_list %}
     <h2>学生{{ student }}</h2>
  {% endfor %}
{% endfor %}

block.super: 获得父模版的内容

{% block content %}
	...
	{{ block.super }}
	...
{% endblock %}

标签的使用:

{% extends %} 须保证为模版中第一个模版标记,否则,模版继承不起作用
{% block %} 一般来说block标签越多越好。“钩子越多越好”
block标签的工作方式是双向的。在同一个模版中不允许定义多个同名的block。

5、Include标签

当html中有大量重复代码时,考虑将重复代码单独放在一个html中,然后在用到这些代码时,通过include标签加入。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1 style="color:#2459a2">hello include</h1>
</body>
</html>
{% extends "base.html" %}
{% load staticfiles %}   # 先load 静态文件
{% block styles %}
    <style>
    h2{
        color:red;
    }
</style>
{% endblock %}

{% block content %}
    {{ block.super }}
    {% for student in student_list %}
        <h2>学生{{ student }}</h2>
    {% endfor %}
    {% include "test.html" %}  # 这样页面将在相应位置显示:hello include
{% endblock %}

实践笔记

{% if scenerys|length > 0 %} 模版语言 判断列表长度
{% for obj in teachers|slice:"0:3" %} {# 模版语言:列表切片,0-3 不含3 #}
模版日期格式化 {{ obj.create_time|date:'Y-m-d H:i:s' }}
{% 标签 参数 as a %} 将标签返回的变量赋值a

posted @   Bruce_JRZ  阅读(6)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
点击右上角即可分享
微信分享提示