Django重新整理
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重新整理的更多相关文章
- Django知识点整理
什么是web框架 框架,即framework,特指为解决一个开放性问题而设计的具有一定约束性的支撑结构,使用框架可以帮你快速开发特定的系统,简单地说,就是你用别人搭建好的舞台来做表演. web应用 访 ...
- django笔记整理
Django复习: MTV模型: manager启动服务→urls找到路径→(找到views视图函数或者做路由分发)→视图函数处理相关逻辑,返回一个模板或者是字符串: ---------------- ...
- Django重新整理4---ModelForm-set(批量处理数据)
1. #引用modelformset from django.forms.models import modelformset_factory #必须继承forms.ModelForm! class ...
- Django重新整理3
Forms组件 1.在models.py中我们建立一个新的表关系: class UserInfo(models.Model): user=models.CharField(max_length=32) ...
- Django重新整理2
Auth认证: 1.分配路由和创建视图函数 2.在视图函数中引用Django为我们提供的用户认证组建Auth 3.直接进行判断: def login(request): if request.meth ...
- Django ORM整理
字段类型 # 自增长 Auto = models.AutoField() BigAuto = models.BigAutoField() # 二进制 Binary = models.BinaryFie ...
- Django(一) 安装使用基础
大纲 安装Django 1.创建Django工程 2.创建Django app 3.写一个简单的登录注册相应页面 4.获取用户请求信息并处理 5.前后端交互 6.Django 请求 生命周期 跳转到 ...
- python学习博客地址集合。。。
python学习博客地址集合... 老师讲课博客目录 http://www.bootcdn.cn/bootstrap/ bootstrap cdn在线地址 http://www.cnblogs. ...
- 老男孩老师的博客地址 - 转自devops1992
害怕他那天不让人看了,所以我就复制一份到我自己的博客里. http://www.bootcdn.cn/bootstrap/ bootstrap cdn在线地址 http://www.cnblogs. ...
随机推荐
- JQuery UI - selectable
·概述 Selectable插件允许用户对指定的元素进行选中的动作.此外还支持按住Ctrl键单击或拖拽选择多个元素. 官方示例地址:http://jqueryui.com/demos/selectab ...
- java求几个数字的和输出详细步骤
设计思想:要求几个数字的和,就要把输入的字符串转换成浮点型,然后求和再输出. 程序流程图: 程序源代码: //此程序用于从命令行接收多个数字,就和并输出. //作者:赵东睿 //2015.9.26 p ...
- Java50道经典习题-程序40 字符串排序
题目:根据字符串内字符的ASCII码值对字符串数组进行排序.分析:字符串用ASCII码比较大小,规则是:1.比较首字母的ASCII码大小2.若是前面的字母相同,则比较之后的字母的ASCII码值3.若是 ...
- 割点(Tarjan算法)【转载】
本文转自:www.cnblogs.com/collectionne/p/6847240.html 供大家学习 前言:之前翻译过一篇英文的关于割点的文章(英文原文.翻译),但是自己还有一些不明白的地方, ...
- MySQL - ODBC安装错误问题!
MySQL的ODBC安装时候可能会出错,主要原因是缺少VC支持库,需要2010版本的VC支持库!!X86和X64分别对应MySQL对应的ODBC,不能安装一个两个都搞定,如果需要安装两个ODBC驱动, ...
- EXTJs前后台交互 常用哦3种方式
<1>Ajax交互方式 Ext.Ajax.request( { //被用来向服务器发起请求默认的url url : "", //请求时发送后台的参数,既可以是Json对 ...
- uint8_t / uint16_t / uint32_t /uint64_t 是什么数据类型
在nesc的代码中,你会看到很多你不认识的数据类型,比如uint8_t等.咋一看,好像是个新的数据类型,不过C语言(nesc是C的扩展)里面好像没有这种数据类型啊!怎么又是u又是_t的?很多人有这样的 ...
- 关于cuda拷贝的速度测试
由于没有使用profiler,仅仅通过简单的传输函数测试,如下测试了10000个点,1000000个点,100000000个点的速度: 均按时钟周期来计时,通过MAX调整数据 int main(){ ...
- Hbase0.98.0完全分布式搭建---【使用外部zookeeper】
Hbase是一个分布式的实时数据库,他可以基于hadoop的hdfs,S3等分布式存储系统.而且使用zookeeper来通信(查询元数据和获取数据所在位置等功能) 本文的Hbase使用的是hadoop ...
- js按回车事件提交
$(document).keyup(function (event) { if (event.keyCode == "13") { document.getElementById( ...