Django (d) ----- view layer, the template layer

Django (d) ----- view layer, the template layer

View layer

A view function (class), referred to as a view, Python is a simple function (class) that accepts the request and returns Web Web response.

The response may be a page's HTML content, a redirect, a 404 error, an XML document, or a picture.

The view function value must be returned by one, and return value data types must HttpResponse object

form form

form form to upload a file, you need to pay attention to:

1. method必须改成post
2. enctype也要改成formdata格式
#django针对不同类型的数据,会自动解析并放到不同的方法中
#获取文件通过FILES方法获取
file_obj = request.FILES.get('文件名')   #获取文件对象

JasonResponse

Actual project, separate front and rear ends, the front and rear ends of the data in order to Duanjiapo Hu, need json string (dictionary) Normally, only the rear end corresponding to url written interfaces, through which the front end can be interface to access data

Front and rear ends of the sequence Method deserialization

#python后端
json.dumps
json.loads

#js
JSON.stringify
JSON.parse
def index(request):
    # json会自动帮你对中文进行转码
    user_dic = {'name':'simple是我','password':'123'}
    
    #ensure_ascii设置为false可以取消自动转码
    json_str = json.dumps(user_dic,ensure_ascii=False)
    return HttpResponse(json_str)
-------------------------------------------------------------------
    return JsonResponse(user_dic,json_dumps_params={'ensure_ascii':False})
    l = [1,2,3,4,5,6,7,]
    # JsonResponse默认是序列化字典用的 如果你想序列化其他数据类型(json模块能够序列化的) 你需要加一个safe参数
    return JsonResponse(l,safe=False)

FBV and CBV

FBV

Based on the view function

#FNV写法  路由 >>> 视图函数内存地址
url(r'^index/',views.index),

CBV

CBV basic wording

Based on the view class

# CBV写法
url(r'^login/',views.MyLogin.as_view())

as_view is a function (function name in parentheses implementation of the highest priority)

When the project starts, it will automatically execute as_view method

#views文件中
class MyLogin(View):
    def get(self,request):
        print('我是MyLogin里面的get方法')
        return render(request,'login.html')

    def post(self,request):
        print('我是MyLogin里面的post方法')
        return HttpResponse('post')

CBV source

@classonlymethod
def as_view(cls, **initkwargs):
    def view(request, *args, **kwargs):  # 闭包函数
        self = cls(**initkwargs)  # cls是我们自己写的类 MyLogin  self是我们自己定义的类的对象
        # 在看源码的时候 你一定要把握住一个顺序 对象在查找属性和方法的时候
        # 先从对象自身找 再去产生对象的类中找 再去类的父类中找
        return self.dispatch(request, *args, **kwargs)
    return view

def dispatch(self, request, *args, **kwargs):
    # 判断当前请求方式在不在默认的八个方法内
    # 1.先以GET请求为例
    if request.method.lower() in self.http_method_names:
        # 利用反射去我们自己定义类的对象中查找get属性或者是方法  getattr(obj,'get')
        # handler = get方法
        handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
    else:
        handler = self.http_method_not_allowed
    return handler(request, *args, **kwargs)  # 调用get方法


CBV decorator

  1. Recommended wording:@method_decorator(outter)
  2. Mounted on the top of the class, you can specify which function to install@method_decorator(outter,name='post')
  3. By adding decorator to dispatch, it is equivalent to the function decorator added in all classes
from django.utils.decorators import method_decorator
# 2.可以指定给谁装
# @method_decorator(outter,name='post')
# @method_decorator(outter,name='dispatch')
class MyLogin(View):
    @method_decorator(outter)
    def dispatch(self, request, *args, **kwargs):  # 如果你想在视图函数执行之前 做一些操作 你可以在你的CBV中定义dispatch方法来拦截
        return super().dispatch(request,*args,**kwargs)
    
    # @outter  # 1.直接写
    # @method_decorator(outter) 
    def get(self,request):
        print('我是MyLogin里面的get方法')
        return render(request,'login.html')
    # @outter
    def post(self,request):
        print('我是MyLogin里面的post方法')
        time.sleep(1)
        return HttpResponse('post')

Template layer

Template syntax

There are only two writing format

{{}}  变量相关
{%%}  逻辑相关

Template by value

Biography python data types

Template data types supported by value

Concluded: python all the basic data types supported by value

return render(request, 'test.html', locals())
#通过locals()方法,可以获取该名称空间中的所有名字,并传给HTML页面

Transfer function names

When the transfer function to the HTML page name, template syntax will automatically call the function in parentheses, and the return value of a function as a showcase basis,

Template syntax does not support the function parameter passing , which means that you can only be passed to html page does not need to call the function parameter passing

Pass the class name

==> long as it is bracketed call is transferred to the html page will automatically call the brackets

自动加括号实例化产生对象
</p>
<p>传对象:{{ obj }}</p>
<p>{{ obj.get_self }}</p>
<p>{{ obj.get_cls }}</p>
<p>{{ obj.get_func }}</p>

filter

语法结构:  |
#模板语法之过滤器,会自动将|左边的数据当前过滤器的第一个参数传入:右边的当做第二个参数

#<p>统计长度(如果无法统计默认返回0):{{ s|length }}</p>
#<p>加法运算(内部异常捕获 支持数字相加 字符串拼接 都不符合返回空):{{ n|add:f }}</p>
#<p>切片操作 顾头不顾尾 也支持步长:{{ l|slice:'0:5:2' }}</p>
#<p>判断是否有值(有值展示值本身 没值展示默认值):{{ is_value|default:'is_value变量名指向的值为空' }}</p>
#<p>自动转成文件大小格式:{{ file_size|filesizeformat }}</p>
#<p>截取文本内容(字符) 截取五个字符 三个点也算:{{ s|truncatechars:8 }}</p>
#<p>截取文本内容(按照空格计算) 截取五个单词 三个点不算 :{{ s1|truncatewords:5 }}</p>

默认情况下 是不会自动帮你转换成前端html标签 防止恶意攻击
#<p>展示带有标签的文本:{{ sss }}</p>
#<p>展示带有标签的文本:{{ sss|safe }}</p>

Front and rear end unescaping

Automatically help you convert front-end html tag

The front

​ |safe

Backend

    ```python

from django.utils.safestring import mark_safe
sss = "

My h2 tag

"
res = mark_safe(sss)
```

label

for loop

{% for foo in l %}
    <p>{% forloop %}</p>    #forloop内置的参数,
    <p>{{ foo }}</p>
{% endfor %}

for if used in combination

{% for foo in l %}
    {% if forloop.first %}
        <p>for循环的开始</p>
    {% elif forloop.last %}
        <p>for循环的结束</p>
    {% else %}
        <p>{{ foo }}</p>
    {% endif %}
    {% empty %}
        <p>当for循环的对象是空的时候会执行</p>
{% endfor %}

Template syntax values

Only one way to break the uniform application period

comp_dic = {'username':'jason','hobby':['read','study',['run','rap',{'age':18}]]}

#通过模板语法的取值,用.的方式
<p>{{ comp_dic.hobby.2.2.age }}</p>

#当数据是通过比较复杂的...获取到的,后续又需要经常使用,可以给该数据起别名,别名只能在with内部使用
{% with comp_dic.hobby.2.2.age as age  %}
    <p>{{ age }}</p>
    <p>{{ comp_dic.hobby.2.2.age }}</p>
{% endwith %}

Custom filters and labels

There are three must first prepare

1. In an application under the name of a new name must be called templatetags folder

2. Create a new folder any name in the file py file

3. You must write the code in the following two py file

from django.template import Library
    
register = Library()
# 之后就可以利用register来自定义过滤器和标签

Use custom filter

@register.filter(name='过滤器名')

#需要先在html页面上 加载
{% load mytag %}            #mytag是在templatetags的文件夹自定义的py文件
{{ 1|baby:1  }}
{{ 1|baby:100  }}

# 自定义过滤器  跟默认的过滤器一样 最多只能接受两个参数
@register.filter(name='baby')
def index(a,b):
    return a + b

Use custom labels

@register.simple_tag(name='标签名')

# 自定义标签   可以接受任意多个参数
@register.simple_tag(name='mytag')
def mytag(a,b,c,d):
    return '%s?%s?%s?%s'%(a,b,c,d)

<p>自定义标签的使用 可以接受多个参数 参数与参数之间必须空格隔开</p>
{% load mytag %}
{% mytag 'a' 'b' 'c' 'd' %}
{% load mytag %}

From the tag defined filters can use custom logic statements may not

Custom inclusion_tag

Is a function of the outside world can accept the argument passed and then passed to a html page for page rendering is complete after the data, rendering a good page

Face, into a place to call inclusion_tag

# 自定义inclusion_tag
@register.inclusion_tag('mytag.html',name='xxx')
def index666(n):
    l = []
    for i in range(n):
        l.append('第%s项'%i)
    return locals()             # 将l直接传递给mytag.html页面

#自定义inclusion_tag的使用 ,当你需要使用一些页面组件的时候 
#并且该页面组件需要参数才能够正常渲染 你可以考虑使用inclusion_tag
{% load mytag %}
{% xxx 5 %}

Inherited template

Need to advance on the page you want to use, delineation of the area, after inheriting the time, you can use the designated areas

If you do not designate any area, you can not modify the content of the page

Inherited template

1. On the first page you want to inherit through the block demarcated area you might want to change the future

2. On the sub-pages to inherit extends

3. Use block content automatically prompted to select the area you want to modify

{% extends 'home.html' %}   #通过该方法,可以继承指定页面
# 在页面上利用block划定你以后可能想改的区域  content为指定的区域命名
{% block content %}
{% endblock %}

#在模板页面中通过block修改content中的内容
{% block content %}
修改模板中content区域内容
{% endblock %}

On the sub-pages continue to use the contents of the parent page

 {{ block.super }}

Importing templates

将html页面当做模块的直接导入使用

{% include 'bform.html' %}

Guess you like

Origin www.cnblogs.com/samoo/p/11938747.html