65 组件 静态文件相关 视图

主要内容:

1 组件

  a : 定义:可以将常用的页面内容如导航条,页尾信息等组件保存在单独的文件中,然后在需要使用的地方按如下语法导入即可

  b : 语法:  {% include '组件名'%}

2 静态文件相关:

       a : 语法: {% load static %}

  {% load static %}
    <link href="{% static 'bootstrap-3.3.7/css/bootstrap.css' %}" rel="stylesheet">
    <link href="{% static 's14_files/dashboard.css' %}" rel="stylesheet">

   获取静态前缀:get_static_prefix

{% load static %}
    <link href="{% get_static_prefix %}bootstrap-3.3.7/css/bootstrap.css" rel="stylesheet">
    <link href="{% get_static_prefix %}s14_files/dashboard.css" rel="stylesheet">

  两个的区别: 第一种是jango自动拼接成的路径, 第二种是自己手动拼接成的路径

3 simple_tag

4 inclusion_tag 

  a : 定义: 多用于返回html代码片段

扫描二维码关注公众号,回复: 3499973 查看本文章

  b : 课上讲解: 分页

5 视图

  1:CBV 和 FBV

    FBV: 我们之前写的基于函数的view, 就叫FBV

    CBV: 把函数写成基于类的, 就叫CBV

from django.views import View
class AddPress(View):
    def get(self, request):
        return render(self.request, 'add_press22.html')
    def post(self, request):
        add_name = self.request.POST.get('name')
        Press.objects.create(name=add_name)
        return redirect('/press_list/')

  url中的代码段:

    url(r'^add_press/', views.AddPress.as_view()),

  CBV的执行流程:

    1 AddPress.as_view()  —— 》 view函数

    2 当请求到来的时候执行view函数:

      1. 实例化自己写的类:   self = cls(**initkwargs)

      2. self.request = request

      3 . 执行dispatch(request, *args, **kwargs)

        1. 自己没有该方法, 执行父类中的此方法

          ? 判断请求方式是否被允许

            允许的情况:  handler = 通过反射获取get 或者 post 方法

            不允许:         handler = 不允许的方法

            handler(request, *args, **kwargs)

        2 . 返回HttpResponse对象

      4 . 返回HttpResponse对象 给jango

        

  2 request:

 # print(request.method)
    # print(request.GET)       #取url上的值
    # print(request.POST)      # 取form表单提交的数据
    # print(request.path_info)  #路径
    # print(request.encoding)
    # print(request.get_host())     #127.0.0.1:8000
    # print(request.get_full_path())  #/test/
    # print(request.is_secure())  #/False
    # print(request.is_ajax())      #False

  3 response

    1: 常见的三个响应

      from django.shortcuts import render, HttpResponse, redirect
         1. HttpResponse    HttpResponse('字符串')  
         2. render(request,'html文件名',{})    —— 》 HTML代码
         3. redirect(跳转的地址)

    2 : JsonResponse       : json序列化
       HttpResponse(json.dumps(ret))  # Content-Type: text/html; charset=utf-8
         JsonResponse(ret)      # Content-Type: application/json
import json
from django.http import JsonResponse
def json_data(request):
    dic = {'name': 'alex', 'age': 122}
    # return JsonResponse(dic)
    return HttpResponse(json.dumps(dic))

  

猜你喜欢

转载自www.cnblogs.com/gyh412724/p/9762620.html
65