1.母版的继承

#base
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
{% block title %}
<title>Title</title>
{% endblock %}
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<style>
*{
margin: 0;
padding: 0;
}
.header{
width: 100%;
height: 50px;
background-color: #369; }
</style>
</head>
<body>
<div class="header"></div> <div class="container">
<div class="row">
<div class="col-md-3">
{% block menu %}
<div class="panel panel-success">
<div class="panel-heading">Panel heading without title</div>
<div class="panel-body">
<p><a href="/index/">首页</a></p>
<p><a href="/order/">订单</a></p>
<p> <a href="/shopping_list/">商品列表</a></p>
</div>
</div>
{% endblock %}
</div>
<div class="col-md-9">
#注意 定义一个盒子:关键字:block 必须是这个字!!!后边加自己起的名字
#{%block content%}
{% block content %}
<h3>welcome!</h3> {% endblock content%}
</div>
</div>
</div> </body>
</html> #index,html
#必须是 extends 这个关键字 ,后边跟着继承的哪个页面
#{%extends "base.html"%}
{% extends "base.html" %}

{% block content %}
{{ block.super }} <div class="jumbotron">
<h1>Hello, world!</h1>
<p>...</p>
<p><a class="btn btn-primary btn-lg" href="#" role="button">Learn more</a></p>
</div>
{% endblock %} {% block title %}
<title>首页</title>
{% endblock %}

2.orm小的项目整理

2.1新建的项目里先生成表

#models

class Book(models.Model):
nid=models.AutoField(primary_key=True)
title=models.CharField(max_length=32)
price=models.DecimalField(max_digits=8,decimal_places=2) # 999999.99
pub_date=models.DateTimeField() # "2012-12-12"
publish=models.ForeignKey(to="Publish",on_delete=models.CASCADE) # 级联删除
authors=models.ManyToManyField(to="Author")
def __str__(self):
return self.title class Publish(models.Model):
nid = models.AutoField(primary_key=True)
name=models.CharField(max_length=32)
email=models.CharField(max_length=32)
def __str__(self):
return self.name class Author(models.Model):
nid = models.AutoField(primary_key=True)
name=models.CharField(max_length=32)
age=models.IntegerField()
email=models.CharField(max_length=32)
ad=models.OneToOneField(to="AuthorDetail",on_delete=models.CASCADE)
def __str__(self):
return self.name class AuthorDetail(models.Model):
addr=models.CharField(max_length=32)
tel=models.IntegerField()
#author=models.OneToOneField("Author",on_delete=models.CASCADE)
def __str__(self):
return self.addr

2.2进行数据库的迁移

2.3添加表里的数据,先从从表里添加数据,再从主表里添加数据,或者直接粗暴的在数据库里添加

2.4分配路由,写视图函数

#urls
from django.contrib import admin
from django.urls import path,re_path from app01 import views urlpatterns = [
path('admin/', admin.site.urls),
path("books/",views.book_view),
re_path("^$",views.book_view),
path("books/add/",views.book_add),
re_path("^books/edit/(?P<edit_book_id>\d+)$",views.book_edit),
re_path("^books/delete/(?P<del_book_id>\d+)$",views.book_del),
]

2.5函数

def book_view(request):
book_list=Book.objects.all()
return render(request,"book_view.html",{"book_list":book_list}) def book_add(request):
if request.method=="GET":
publish_list=Publish.objects.all()
author_list=Author.objects.all()
return render(request,"book_add.html",{"publish_list":publish_list,"author_list":author_list})
else:
title=request.POST.get("title")
price=request.POST.get("price")
pub_date=request.POST.get("pub_date")
publish_id=request.POST.get("publish_id")
authors=request.POST.getlist("authors")
print(request.POST)
print(authors) book=Book.objects.create(title=title,price=price,pub_date=pub_date,publish_id=publish_id)
book.authors.add(*authors)
return redirect("/books/") def book_edit(request,edit_book_id):
edit_book = Book.objects.filter(pk=edit_book_id).first()
if request.method=="GET":
publish_list = Publish.objects.all()
author_list = Author.objects.all()
return render(request,"book_edit.html",{"edit_book":edit_book,"publish_list":publish_list,"author_list":author_list}) else:
title = request.POST.get("title")
price = request.POST.get("price")
pub_date = request.POST.get("pub_date")
publish_id = request.POST.get("publish_id")
authors = request.POST.getlist("authors")
print(request.POST)
print(authors)
Book.objects.filter(pk=edit_book_id).update(title=title,price=price,pub_date=pub_date,publish_id=publish_id)
edit_book.authors.set(authors) return redirect("/books/") def book_del(request,del_book_id):
Book.objects.filter(pk=del_book_id).delete()
return redirect("/books/")

2.6 tmplates

#book_add.html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> </head>
<body> <h3>添加书籍</h3>
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<form action="" method="post">
{% csrf_token %}
<div class="form-group">
<label for="title">书籍名称</label>
<input class="form-control" type="text" name="title" id="title">
</div>
<div class="form-group">
<label for="price">价格</label>
<input class="form-control" type="text" name="price" id="price">
</div>
<div class="form-group">
<label for="pub_date">出版日期</label>
<input class="form-control" type="date" name="pub_date" id="pub_date">
</div>
<div class="form-group">
<label for="pub_date">出版社</label>
<select name="publish_id" id="" class="form-control">
{% for publish in publish_list %}
<option value="{{ publish.pk }}">{{ publish.name }}</option>
{% endfor %}
</select>
</div> <div class="form-group">
<label for="pub_date">作者</label>
<select name="authors" id="" class="form-control" multiple>
{% for author in author_list %}
<option value="{{ author.pk }}">{{ author.name }}</option>
{% endfor %}
</select>
</div> <input type="submit" value="提交" class="btn btn-default pull-right"> </form> </div>
</div>
</div> </body>
</html> #book_edit.html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> </head>
<body> <h3>编辑书籍</h3>
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<form action="" method="post">
{% csrf_token %}
<div class="form-group">
<label for="title">书籍名称</label>
<input class="form-control" value="{{ edit_book.title }}" type="text" name="title" id="title">
</div>
<div class="form-group">
<label for="price">价格</label>
<input class="form-control" value="{{ edit_book.price }}" type="text" name="price" id="price">
</div>
<div class="form-group">
<label for="pub_date">出版日期</label>
<input class="form-control" value="{{ edit_book.pub_date|date:'Y-m-d' }}" type="date" name="pub_date" id="pub_date">
</div>
<div class="form-group">
<label for="pub_date">出版社</label>
<select name="publish_id" id="" class="form-control">
{% for publish in publish_list %}
{% if edit_book.publish == publish %}
<option selected value="{{ publish.pk }}">{{ publish.name }}</option>
{% else %}
<option value="{{ publish.pk }}">{{ publish.name }}</option>
{% endif %}
{% endfor %} </select>
</div> <div class="form-group">
<label for="pub_date">作者</label>
<select name="authors" id="" class="form-control" multiple>
{% for author in author_list %}
{% if author in edit_book.authors.all %}
<option selected value="{{ author.pk }}">{{ author.name }}</option>
{% else %}
<option value="{{ author.pk }}">{{ author.name }}</option>
{% endif %}
{% endfor %}
</select>
</div> <input type="submit" value="提交" class="btn btn-default pull-right"> </form> </div>
</div>
</div> </body>
</html> #book_view.html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="/static/bootstrap/css/bootstrap.css">
</head>
<body> <h3>查看书籍</h3>
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<a href="/books/add/" class="btn btn-primary">添加书籍</a>
<table class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th>编号</th>
<th>书籍名称</th>
<th>价格</th>
<th>出版日期</th>
<th>出版社</th>
<th>作者</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{% for book in book_list %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{ book.title }}</td>
<td>{{ book.price }}</td>
<td>{{ book.pub_date|date:"Y-m-d" }}</td>
<td>{{ book.publish.name }}</td>
<td>
{% for author in book.authors.all %}
<span>{{ author.name }}</span>
{% if not forloop.last %}
,
{% endif %}
{% endfor %} </td> <td>
<a href="/books/delete/{{ book.pk }}" class="btn btn-danger btn-sm">删除</a>
<a href="/books/edit/{{ book.pk }}" class="btn btn-warning btn-sm">编辑</a>
</td>
</tr> {% endfor %} </tbody>
</table>
</div>
</div>
</div>
<script src="/static/js/jquery.js"></script>
<script>
$("h3").click(function () {
$(this).css("color","green")
})
</script>
</body>
</html>

3json模块

3.1json其实就是一个模块,把字符串类型的转换成我们想要的数据类型

d = {"name":"alex"}
print(type(d))
#<class 'dict'> s = json.dumps(d)
print(type(s))
#<class 'str'> #注意:json中的dumps是把其他数据类型转换成字符串数据类型
#注意:json中的loads是把字符串数据类型转换成原有的数据类型

4.AJAX

4.1利用Ajax请求进行简单的求和(没有动态传参的Ajax)

#urls
path('index/', views.index),
#views中
def index(request):
return render(request,"index.html") #templayes中
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="/static/js/jquery-3.3.js"></script>
</head>
<body> <h4>INDEX页面</h4>
<button class="btn">提交Ajax</button>
<p class="show"></p>
<hr>
{% csrf_token %}
<input type="text" id="num1"> + <input id="num2" type="text"> = <input id="ret" type="text"><button class="cal">计算</button> <script>
//  传参Ajax请求

$(".cal").click(function () {

    var num1=$("#num1").val();
var num2=$("#num2").val(); $.ajax({
#返回的地址
url:"/cal/",
type:"post",
data:{
num1:num1,
num2:num2,
csrfmiddlewaretoken:$("[name='csrfmiddlewaretoken']").val() },
success:function (response) {
console.log(response);
$("#ret").val(response)
} }) })
</script> </body> </html>

#urls
path('cal/', views.cal),

#views中
def cal(request):
num1=request.POST.get("num1")
num2=request.POST.get("num2")
ret=int(num1)+int(num2)
return HttpResponse(str(ret))

4.2利用Ajax进行登录

4.2.1分配路由写视图函数

def login(request):
if request.method == "POST":
res={"user":None,"error":""}
user=request.POST.get("user")
pwd=request.POST.get("pwd") user_obj=UserInfo.objects.filter(user=user,pwd=pwd).first()
if user_obj:
res["user"]=user
else:
res["error"]="用户名或者密码错误!"
return HttpResponse(json.dumps(res)) else:
return render(reqeust,"login.html") #templades中
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="/static/js/jquery-3.3.js"></script> </head>
<body> <form>
用户名 <input type="text" id="user">
密码 <input type="password" id="pwd">
<input type="button" value="提交" id="login_btn"><span class="error"></span>
{% csrf_token %} </form> <script> $("#login_btn").click(function () { // 发送Ajax请求登录认证 $.ajax({
url:"/login/",
type:"post",
data:{
#date是客户端往服务器传过去的数据
user:$("#user").val(),
pwd:$("#pwd").val(),
csrfmiddlewaretoken:$("[name='csrfmiddlewaretoken']").val()
},
success:function (response) {
console.log(response); // json字符串
var res=JSON.parse(response);
console.log(res);
if (res.user){
// 登陆成功
location.href="/index/"
}else{
// 登录失败
$(".error").html(res.error).css("color","red");
setTimeout(function () {
$(".error").html("")
},1000)
} }
})
}) </script>
</body>
</html>

Django重新整理的更多相关文章

  1. Django知识点整理

    什么是web框架 框架,即framework,特指为解决一个开放性问题而设计的具有一定约束性的支撑结构,使用框架可以帮你快速开发特定的系统,简单地说,就是你用别人搭建好的舞台来做表演. web应用 访 ...

  2. django笔记整理

    Django复习: MTV模型: manager启动服务→urls找到路径→(找到views视图函数或者做路由分发)→视图函数处理相关逻辑,返回一个模板或者是字符串: ---------------- ...

  3. Django重新整理4---ModelForm-set(批量处理数据)

    1. #引用modelformset from django.forms.models import modelformset_factory #必须继承forms.ModelForm! class ...

  4. Django重新整理3

    Forms组件 1.在models.py中我们建立一个新的表关系: class UserInfo(models.Model): user=models.CharField(max_length=32) ...

  5. Django重新整理2

    Auth认证: 1.分配路由和创建视图函数 2.在视图函数中引用Django为我们提供的用户认证组建Auth 3.直接进行判断: def login(request): if request.meth ...

  6. Django ORM整理

    字段类型 # 自增长 Auto = models.AutoField() BigAuto = models.BigAutoField() # 二进制 Binary = models.BinaryFie ...

  7. Django(一) 安装使用基础

    大纲 安装Django 1.创建Django工程 2.创建Django app 3.写一个简单的登录注册相应页面 4.获取用户请求信息并处理 5.前后端交互 6.Django 请求 生命周期  跳转到 ...

  8. python学习博客地址集合。。。

    python学习博客地址集合...   老师讲课博客目录 http://www.bootcdn.cn/bootstrap/  bootstrap cdn在线地址 http://www.cnblogs. ...

  9. 老男孩老师的博客地址 - 转自devops1992

    害怕他那天不让人看了,所以我就复制一份到我自己的博客里. http://www.bootcdn.cn/bootstrap/  bootstrap cdn在线地址 http://www.cnblogs. ...

随机推荐

  1. C/C++中有关字长与平台无关的整数类型

    在C/C++中,整型的长度跟编译器相关,编译器的实现取决于CPU. 比如TC++是DOS16下的应用程序,DOS16是16位的操作系统,所以TC++中sizeof(int)==16:同理win32中s ...

  2. Java 分析模板方法设计模型

    http://www.cnblogs.com/maowang1991/archive/2013/04/15/3023236.html //父类 abstract class Operate{ prot ...

  3. easyui rowspan

    第一种写法 columns: [ [ { field: 'depName', title: '部门', rowspan: 2, width: '100px', align: 'center' }, { ...

  4. c#写对象来读取TXT文本文件

    本博文让你知道怎样写对象,怎样读取文本文件,怎样根据实际条件判断与获取需要的文本行.参考下面网友的问题,根据源文来看,有些行输出的格式,需要把“,”替换为空格. 第一行还附加入后面的子行每一行的后面, ...

  5. [Algorithm]线性表

    一. 线性表基础算法 1.线性表插入操作 1 // 线性表插入操作(在第i(1≤i≤L.length+1)个位置上插入新元素elem) 2 bool InsertSeq( SeqList& L ...

  6. 洛谷P3604 美好的每一天(莫队)

    传送门 由乃的题还是一如既往的可怕…… 先放上原题解 标解: 一个区间可以重排成为回文串,即区间中最多有一个字母出现奇数次,其他的都出现偶数次 发现这个和  类似 这样如果一个区间的  和为  或者  ...

  7. DB2存储过程标准

    CREATE OR REPLACE PROCEDURE "FCT"."PROC_FCT_DSB_SERIES"(IN ACCOUNTING_DATE DATE) ...

  8. 模板 可并堆【洛谷P3377】 【模板】左偏树(可并堆)

    P3377 [模板]左偏树(可并堆) 如题,一开始有N个小根堆,每个堆包含且仅包含一个数.接下来需要支持两种操作: 操作1: 1 x y 将第x个数和第y个数所在的小根堆合并(若第x或第y个数已经被删 ...

  9. 树状数组 二维偏序【洛谷P3431】 [POI2005]AUT-The Bus

    P3431 [POI2005]AUT-The Bus Byte City 的街道形成了一个标准的棋盘网络 – 他们要么是北南走向要么就是西东走向. 北南走向的路口从 1 到 n编号, 西东走向的路从1 ...

  10. 10.Find All Anagrams in a String(在一个字符串中发现所有的目标串排列)

    Level:   Easy 题目描述: Given a string s and a non-empty string p, find all the start indices of p's ana ...