一、路由控制

二、视图层

三、模板层

四、模型层、单表操作、多表操作

五、什么是ajax

一、路由控制

  补充点(什么是web应用?)

  网站:BS架构应用程序:B是浏览器  S:server(实现了wsgi协议)+application(我们都在写这个),其实就是CS

  MVC和MTV(django)

    -M:model跟数据库打交道

    -T:Templates模板层,对到mvc的是V这一层

    -V:视图Views路由+V是MVC的c

  web框架:

    application拆分

    a:server b:映射关系  c:模板渲染

    Flask:

    Django

    Tornado

  1.Django中路由的作用

    请求的路径跟视图函数的映射关系

  2.简单的路由配置

    四个参数:第一个正则表达式,第二个函数内存地址,第三个默认值,第四个是别名

  3.分组

    无名:(正则表达式)值分出来当关键字参数传到视图函数

    有名:(?P<名字>正则表达式)值分出来当关键字参数传到视图函数

  4.路由分发

    url(r‘^app01/’,include('app01,urls'))

  5.反向解析

    就是根据别名,取到对应的url地址

      -视图层:reverse('别名'args=())

      -模板层:{% url ‘别名’ 参数 参数 %}

  6.名称空间

    -include(‘app01.urls’,namespance=‘app01’)

    -以后再反向解析:reverse(‘app01:别名’args=())

  7.Django2.0版的path

    -path:路径是准确路径,不是正则表达式了

    -内置了5个转换器

    -自定义转换器

二、视图层

  1.视图函数

  2.HttpResponse对象

    -GET

    -POST

    -FILES

    -path

    -method

    -get_full_path()

    -body

  3.HttpResponse

    -三件套

  4.JsonResponse

    -HttpResponse+json  

  5.CBV和FBV

    -基于类的视图:

      -url配置 类名.as_view()

      -views.py

        class Test(View)

          dispatch:总的分发方法

          def get(self,request)

            return HttpRequest对象

  6.简单文件上传

    -前端页面:form-data

    -视图层:FILES(字典)根据Key值取出来,拿到文件对象

  问题:POST请求是否可以在请求路径中参加参数?可以,从GET中取

    -反向解析传参

      举例:在模板层反向解析出要删除的图书路径

      -url(r'^dlbook/(?P<pk>\d+)',view.deletebook,name='deletebook'),

      -<td><a href="{% url'deletebook' book.pk %}">删除</a></td>

三、模板层

  1.模板简介

    模板语言

  2.模板语法之变量

    -基本用法{{ 变量名 }}

    -深度查询

    {{ 对象.方法 }} 方法不能传参数

    -字典,列表 用.

  3.模板之过滤器

    -data

    -dafault

    -slice

    ...

  4.模板之标签

    {% for %}
      {% for a in 可迭代对象 %}
        {{ a.name }}
        {{ forloop }}
      {% endfor %}
    {% if 条件%}
    {% elif条件 %}
    {% else %}
    {% endif %}     {% with %}:取别名

  5.自定义标签和过滤器

    1.确认app是否已经过期

    2.在app下创建一个包:templatetags

    3.在包中写mytag.py

    4.from django.template import LIbrary

    5.register=Library()

    6.标签:

@register.simple_tag(别名)
def mytesttag(a,b,c)
return a+b+c

     过滤器

@register.filter(别名)
def mytestfilter(别名)
  return a+b

    7.使用标签

{% load mytag %}
标签
{% mytesttag 参数1,参数2,参数3... %}
过滤器
{{ 第一个参数|mytestfilter:'第二个参数' }}

  

  6.模板导入和继承  

    -导入{% include ‘在模板中定义盒子’ %}

    -继承

     

 -先写一个母版,在模板中定义盒子
      {% block content %}
        {% endblock %}
      -使用:
        在其他模板中:
        {% extends % 'base.html'}        
        {% block content %}
        写变化的内容
        {% endblock %}
      {{ block.super }} 会把原来的母版中的内容拿过来

四、模型层、单表操作、多表操作

  -单表:基本查询,双下划线的模糊查询

  -多表:

    基于对象的跨表

    基于双下划线的多表

    聚合查询

      -聚合函数使用

    F,Q查询

      F可以去除字段的值

      Q查询:构造出与或非的关系

    分组查询:

 '''
group by谁就以谁做基表
filter在前表示where
filter在后表示having
values在前表示group by 的字段
values在后表示取值
'''
#查询每个出版社的名称和书籍个数

     

五、什么是ajax

  通过js语言跟后台进行交互的一个东西

    -特点;异步,局部刷新

# 后台views.py

from django.shortcuts import render, HttpResponse

# Create your views here.
def index(request):
if request.method == 'GET':
return render(request, 'index.html')

# 前台index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="/static/jquery-3.3.1.js"></script>
<title>Title</title>
</head>
<body>
<button id="btn">点我向后台发数据</button>
<span id="sp"></span>
<p><button id="btn2">点我</button></p> <br>
<input type="text" id="first">+<input type="text" id="second">=<input type="text" id="sum"><button id="btn3">计算</button>
</body> <script>
$('#btn2').click(function () {
alert(2222)
})
$('#btn').click(function () {
{#alert(1)#}
//往后台提交数据,jquery封装的方法
$.ajax({
'url':'/test/', //请求的路径
'type':'get', //请求的方法
success:function (data) {
//data 是后台返回的数据
console.log(data) $("#sp").text(data)
}
})
}) $("#btn3").click(function () {
/**
var first=$("#first").val()
var second=$("#second").val()
var sum=first+second
$ ("#sum").value(sum)
**/
$.ajax({
url:'/sum/?aa=123',
type:'post',
data:{first:$("#first").val(),second:$("#second").val()},
success:function(data){
//alert(data) $("#sum").val(data)
} })
}) </script>
</html>

案例要求:

  1 后台返回json格式
   2 问?返回render,返回redirect?
 
 基于ajax写一个登陆功能,一旦登陆成功,跳转到百度,登陆失败,在页面显示用户名或密码错误

# views.py

from django.shortcuts import render, HttpResponse

# Create your views here.
def index(request):
if request.method == 'GET':
return render(request, 'index.html') def test(request):
if request.method == 'GET':
import time
# time.sleep(10)
return HttpResponse('hello web') import json
from django.http import JsonResponse
def login(request):
dic={'status':100,'msg':None}
if request.method == 'GET':
return render(request, 'login.html')
# if request.is_ajax():
if request.method=='POST':
name=request.POST.get('name1')
pwd=request.POST.get('pwd2')
if name=='lqz' and pwd=='':
dic['msg'] = '登陆成功'
# 想让前端跳转
# dic['url']='http://www.baidu.com'
dic['url']='/test/'
else:
# 返回json格式字符串
dic['status']=101
dic['msg']='用户名或密码错误'
# return JsonResponse(dic)
return HttpResponse(json.dumps(dic)) def loginjson(request):
dic={'status':100,'msg':None}
if request.method=='POST':
print(request.POST)
print(request.GET)
print(request.body)
xx=request.body.decode('utf-8')
# re是个字典{"name1":"lqz","pwd2":"123"}
re=json.loads(xx)
request.POST=11 print(request.POST)
#
#
# name=re.get('name1')
# pwd=re.get('pwd2')
# print(name)
# print(pwd)
return HttpResponse('ok')

#login登录页面

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="/static/jquery-3.3.1.js"></script>
<title>登陆</title>
</head>
<body>
{#<form action="" method="post">#} <p>用户名:<input type="text" id="name"></p>
<p>密码:<input type="password" id="pwd"></p>
{# 这里不能这么写了#}
{# <input type="submit" value="提交1">#}
{# <button>提交2</button>#}
<input type="button" value="提交3" id="submit"><span id="error"></span>
<input type="button" value="提交json格式" id="submit1"><span id="error"></span> {#</form>#}
</body> <script> $('#submit').click(function () {
$.ajax({
url:'/login/',
type:'post',
data:{name1:$("#name").val(),pwd2:$("#pwd").val()},
success:function (data) {
//后台用JsonResponse返回数据
//data 就会被转成字典
console.log(data)
console.log(typeof data)
//JSON.parse(data) 把字符串类型转成字典
data=JSON.parse(data)
{#JSON.stringify()#}
console.log(typeof dat1)
if(data.status == 100){
//成功,跳转到指定页面
//location.href=地址,前端就会跳转到指定的url
alert(data.msg)
//$("#error").text(data.msg+'正在跳转')
//location.href=data.url
}else{
$("#error").text(data.msg)
} }
})
})
$('#submit1').click(function () {
postdata={name1:$("#name").val(),pwd2:$("#pwd").val()}
$.ajax({
url:'/loginjson/',
type:'post',
//指定提交的编码格式是json格式,
//contentType:'application/json',
//data:JSON.stringify(postdata),
//data:postdata,
data:'123',
success:function (data) {
console.log(data) }
})
}) </script>
</html>

总结:

  1.后端如果返回JsonResponse,前端的ajax内部会自动将json格式字符串转换成字典

  2.后端如果返回HttpResponse,前端的ajax内部不会自动给你转换,拿到的data是字符串形式,需要手动JSON.parse(data)来转成字典

  3.字符串转字典:JSON.parse(data)

   字典转字符串:aa=JSON.stringify(字典对象)

  4.如果前端传的格式是JSON,django不会处理body中的内容,需要自己处理

   只有前端传的格式是urlencoded,form-data格式,django才会给我处理

Django阶段总结与Ajax的更多相关文章

  1. {Django基础七之Ajax} 一 Ajax简介 二 Ajax使用 三 Ajax请求设置csrf_token 四 关于json 五 补充一个SweetAlert插件(了解)

    Django基础七之Ajax 本节目录 一 Ajax简介 二 Ajax使用 三 Ajax请求设置csrf_token 四 关于json 五 补充一个SweetAlert插件(了解) 一 Ajax简介 ...

  2. Django框架 之 基于Ajax中csrf跨站请求伪造

    Django框架 之 基于Ajax中csrf跨站请求伪造 ajax中csrf跨站请求伪造 方式一 1 2 3 $.ajaxSetup({     data: {csrfmiddlewaretoken: ...

  3. day 72 Django基础七之Ajax

    Django基础七之Ajax   本节目录 一 Ajax简介 二 Ajax使用 三 Ajax请求设置csrf_token 四 关于json 五 补充一个SweetAlert插件(了解) 六 同源策略与 ...

  4. day 60 Django基础七之Ajax

      Django基础七之Ajax   本节目录 一 Ajax简介 二 Ajax使用 三 Ajax请求设置csrf_token 四 关于json 五 补充一个SweetAlert插件(了解) 六 同源策 ...

  5. {Django基础七之Ajax} 一 Ajax简介 二 Ajax使用 三 Ajax请求设置csrf_token 四 关于json 五 补充一个SweetAlert插件(了解)

    {Django基础七之Ajax} 一 Ajax简介 二 Ajax使用 三 Ajax请求设置csrf_token 四 关于json 五 补充一个SweetAlert插件(了解)   Django基础七之 ...

  6. Django基础五之Ajax

    Django基础五之Ajax 目录 Django基础五之Ajax 1. Ajax介绍 2. Ajax前后端传值 2.1 方法一HttpResponse直接返回 2.2 方法二使用Json格式返回 2. ...

  7. [Django]网页中利用ajax实现批量导入数据功能

    url.py代码: url(r'^workimport/$', 'keywork.views.import_keywork', name='import_keywork') view.py代码: fr ...

  8. Django补充及初识Ajax

    Django创建一对多表结构 首先现在models.py中写如下代码: from django.db import models # Create your models here. class Bu ...

  9. [Django 1.5] jQuery/Ajax 在Django使用 ,如何更新模板里里变量

    最近希望实现一个页面局部刷新的功能,于是开始查阅ajax资料.幸好现在ajax很多功能都封装在jQuery这个库里面,我们可以很方便去调用.通过学习几个简单的小例子,可以实现简单的前端代码更新,还有重 ...

随机推荐

  1. LODOP设置纸张无效问题

    有的打印机不支持自定义纸张,或不支持当前设置的纸张尺寸,会造成纸张尺寸和代码里设置的尺寸不一致的情况.现象:1.代码一样,纸张语句设置正确,有的打印机纸张正常,有的打印机不正常.2.代码一样,纸张语句 ...

  2. 【leetcode_easy】538. Convert BST to Greater Tree

    problem 538. Convert BST to Greater Tree 参考 1. Leetcode_easy_538. Convert BST to Greater Tree; 完

  3. java工具类学习,系统中用户密码加密总结

    现在项目,用户注册登录部分很少有涉及到了,原因:现在热门开发框架都已经在底层帮我们做了一套用户注册,密码加密,登录认证,权限控制,缓存数据等基本功能. 这有利于项目的快速完成,只需要搬砖码畜们专注于业 ...

  4. ThreadingTCPServer源码解析

    实例 #!/usr/bin/env python #-*- coding:utf-8 -*- import SocketServer class Myserver(SocketServer.BaseR ...

  5. 关于antd form表单getFieldsError方法

    getFieldsError()方法其实只有required:true时,双向数据绑定. {getFieldDecorator('note', { rules: [{ required: true, ...

  6. Eureka报错: Connect to localhost:8761 timed out

    最近整理配置Eureka时, 注册服务后, Eureka服务一直报出如下错误: 如下是我的单台eureka的 application.yml 配置: spring: application: name ...

  7. 数据库基础知识介绍(MySQL)

    一.什么是数据库 1.数据库概念:数据库(Database)是按照数据结构来组织.存储和管理数据的仓库,每个数据库都有一个或多个不同的API接口用于创建,访问,管理,搜索和复制所保存的数据. 2.RD ...

  8. 同一个ip,不同端口号,cookie会被覆盖

    参考资料:https://blog.csdn.net/czh500/article/details/80420459

  9. 《深入理解计算机系统》☞hello world背后的故事

    一步到位的hello world 首先一个简单的C语言版本的hello world例子,保存在文件hello.c中. #include <stdio.h> int main() { pri ...

  10. 洛谷 题解 P2676 【超级书架】

    题解 P2676 [超级书架] 这题就只是一个从大到小的排序而已,用"sort"函数 再用"while"判断奶牛塔的高度是否比书架高度要高 送上代码: #inc ...