Day18 Django之路由系统、模板语言、Ajax、Model

一、路由系统

1.创建Django项目

django-admin startproject day18
cd day18
python3 manage.py startapp app01

2.app01/urls.py配置

from django.conf.urls import url
from django.contrib import admin
from app01 import views urlpatterns = [
#url(r'^admin/', admin.site.urls),
# 传参方式
url(r'^detail/(\d+)/', views.detail),
url(r'^detail2/(\d+)/(\d+)/', views.detail2),
url(r'^detail3/(?P<p1>\d+)/(?P<x2>\d+)/', views.detail3),
]

路由关系:

普通关系:
/index/ -->函数
动态关系:
/index/(\w+)\/ -->函数(参数)
路由分发:
/index/ ->app.url文件 [ /index/(\w+)\/ -->函数(参数)]

app01/views.py

from django.shortcuts import render
from django.shortcuts import HttpResponse # Create your views here. USER_LIST = []
for item in range(94):
temp = {'id':item,'username':'alex'+str(item), 'email':'email'+str(item)}
USER_LIST.append(temp)
def index(request, page):
print(page)
page = int(page)
start = (page - 1) * 10
end = page * 10
user_list = USER_LIST[start:end]
return render(request, 'index.html',{'user_list':user_list}) def detail(request, nid):
nid = int(nid)
current_detail_dict = USER_LIST[nid]
return render(request, 'detail.html',{'current_detail_dict':current_detail_dict})

访问地址:

http://127.0.0.1:8000/detail/11
http://127.0.0.1:8000/detail2/11/22
http://127.0.0.1:8000/detail3/11/22

templates/detail.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>详细信息</title>
</head>
<body>
<ul>
<li>
{{ current_detail_dict.id }}
</li>
<li>
{{ current_detail_dict.username }}
</li>
<li>
{{ current_detail_dict.email }}
</li>
</ul>
</body>
</html>

3.创建manager APP

python3 manage.py startapp manager

4.配置day18/urls.py

from django.conf.urls import url
from django.contrib import admin
from django.conf.urls import url, include
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^web/', include('app01.urls')),
]

5.templates/index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<table>
<tr>
<td>ID</td>
<td>用户名</td>
<td>详细信息</td>
</tr>
{% for item in user_list %}
<tr>
<td>{{ item.id }}</td>
<td>{{ item.username }}</td>
<td><a href="/web/detail/{{ item.id }}/">查看详细信息</a></td>
</tr>
{% endfor %}
</table>
</body>
</html>

访问地址:

http://127.0.0.1:8000/web/index

二、模板语言

模板渲染:
a.模板渲染的过程
b.{{ k1 }} -->索引
c. {% for item in k2 %}
<p>{{ item }},{{ forloop.counter }},{{ forloop.counter0 }},{{ forloop.first }},{{ forloop.last }}</p>
{% endfor %}
d.模板语言的内置方法
e.自定义方法
filter
simple_tag 步骤:
1、创建指定的文件夹,名称不能修改 templatetags
2、创建任意.py,如:xx.py
from django import template
from django.utils.safestring import mark_safe
from django.template.base import render_value_in_context, Node, TemplateSyntaxError
#必须不能变
register = template.Library() #创建函数
@register.filter
def f1(value):
return value + 10 3、在HTML模板的头部执行
{% load xx %}
4、使用
k1 = 'v1'
{{ k1 }} -->v1
{{ k1|f1 }} -->v1666
5、settings.py注册
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app01',
]
filter
限制:传参
支持:模板语言里中if条件
simple_tag
不支持:模板语言中的if条件 f.模板(母版)的继承

1.app01/urls.py

from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
url(r'^template/', views.template),
]

2.app01/views.py

from django.shortcuts import render
from django.shortcuts import HttpResponse def template(request):
return render(request,'template.html',
{'k1':'v1','k2':[11,22,33],'k3':{'username':'alex','email':'email1',}})

3.templates/template.html

{% load xx %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{{ k1 }}
{{ k2.0 }}
{{ k3.username }} {% for item in k2 %}
<p>{{ item }},{{ forloop.counter }},{{ forloop.counter0 }},{{ forloop.first }},{{ forloop.last }}</p>
{% endfor %} {% if k1 == 'v1' %}
<h1>V1</h1>
{% elif k1 == 'v2' %}
<h1>V2</h1>
{% else %}
<h1>other</h1>
{% endif %}
{# filter传多个参数#}
{{ k1|f1:'wang,1234' }}
{# simple_tag传多个参数#}
{% f2 1 2 3 4 5 6 7 8 %} {% if k1|f3 %}
<h1>True</h1>
{% else %}
<h2>False</h2>
{% endif %}
</body>
</html>

4.templates/layout.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户管理</title>
<link rel="stylesheet" href="..." />
<style>
.pg_header{
height: 48px;
background-color: brown;
}
.pg_body .body_menu{
width: 20%;
float: left;
}
.pg_body .body_content{
width: 80%;
float: left;
}
.pg_body{
min-height: 600px;
}
.pg_footer{
height: 200px;
background-color: blue;
}
.active{
background-color: darkcyan;
}
</style>
{% block css %}{% endblock %}
</head>
<body>
<div class="pg_header">
后台系统
</div>
<div class="pg_body">
<div class="body_menu">
<ul>
<li><a id="userinfo" href="/web/userinfo" >用户管理</a></li>
<li><a id="assets" href="/web/assets" >资产管理</a></li>
</ul>
</div>
<div class="body_content">
{% block body %}{% endblock %}
</div>
</div>
<div class="pg_footer"></div>
<script src="xxx"></script>
{% block js %}{% endblock %}
</body>
</html>

templates/userinfo.html

{% extends 'layout.html' %}
{% block body %}
<ul>
{% for item in user_list %}
<li>{{ item.username }},{{ item.salary }}</li>
{% endfor %}
</ul>
{% endblock %} {% block js %}
<script>
document.getElementById('userinfo').className = 'active';
</script>
{% endblock %}

templates/assets.html

{% extends 'layout.html' %}

{% block css %}
{% endblock %} {% block body %}
<table>
{% for item in assets_list %}
<tr>
<td>{{ item.hostname }},{{ item.port }}</td>
</tr>
{% endfor %}
</table>
{# 小组件导入#}
{% include 'child.html' %}
{% include 'child.html' %}
{% include 'child.html' %}
{% endblock %}s {% block js %}
<script>
document.getElementById('assets').className = 'active';
</script>
{% endblock %}

templates/child.html

<form>
<input />
<input />
<input />
<input />
<input />
</form>

5.创建app01/templatetags/xx.py

#!/usr/bin/env python
# coding:utf-8 from django import template
from django.utils.safestring import mark_safe
from django.template.base import render_value_in_context, Node, TemplateSyntaxError import re
register = template.Library() @register.filter
def f1(value, args):
aa = re.split(',', args)
return value + '' + aa[0] + aa[1] @register.simple_tag
def f2(s1, s2, s3, s4, s5, s6, s7, s8):
return s1+s2+s3+s4+s5+s6+s7+s8 @register.filter
def f3(value):
if value == 'v1':
return True
else:
return False

三、Ajax

Ajax
a.存放在static下
b.settings.py中导入
c.HTML导入 $.ajax({
url: '/index',
type: 'POST',
data: {'username': 'wang', 'password': ''},
success: function(data){
//当后台return之后,该函数自动运行
//data就是后台返回的数据
}
}) 注意:
1、浏览器中XMLHttpRequest对象(原生的Ajax)
2、jQuery调用XMLHttpRequest对象(jQuery ajax)
3、跨域Ajax
浏览器同源策略:
Ajax只能给自己的域名发请求
跨域名,浏览器做拦截(jsonp、跨域资源共享-header)

1.day18/settings.py

STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)

2.app01/urls.py

from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
#url(r'^admin/', admin.site.urls),
# 传参方式
# url(r'^detail/(\d+)/', views.detail),
# url(r'^detail2/(\d+)/(\d+)/', views.detail2),
# url(r'^detail3/(?P<p1>\d+)/(?P<x2>\d+)/', views.detail3),
url(r'^template/', views.template),
#url(r'^extend/', views.extend),
url(r'^assets/', views.assets),
url(r'^userinfo/', views.userinfo),
url(r'^ajax_demo/', views.ajax_demo),
]

3.app01/views.py

from django.shortcuts import render
from django.shortcuts import HttpResponse
import json # Create your views here. USER_LIST = []
for item in range(94):
temp = {'id':item,'username':'alex'+str(item), 'email':'email'+str(item)}
USER_LIST.append(temp)
def index(request, page):
print(page)
page = int(page)
start = (page - 1) * 10
end = page * 10
user_list = USER_LIST[start:end]
return render(request, 'index.html',{'user_list':user_list}) def detail(request, nid):
nid = int(nid)
current_detail_dict = USER_LIST[nid]
return render(request, 'detail.html',{'current_detail_dict':current_detail_dict}) def template(request):
return render(request,'template.html',
{'k1':'v1','k2':[11,22,33],'k3':{'username':'alex','email':'email1',}}) # def extend(request):
# return render(request, 'extend.html') def assets(request):
assets_list = []
for i in range(10):
temp = {'hostname':'h1'+str(i),'port':80}
assets_list.append(temp)
return render(request, 'assets.html',{'assets_list':assets_list}) def userinfo(request):
user_list = []
for i in range(10):
temp = {'username': 'wang' + str(i), 'salary': 8000}
user_list.append(temp)
return render(request, 'userinfo.html',{'user_list':user_list}) def ajax_demo(request):
if request.method == 'POST':
ret = {'status': False, 'message':''}
user = request.POST.get('user', None)
pwd = request.POST.get('pwd', None)
if user == '' and pwd == '':
ret['status'] = True
return HttpResponse(json.dumps(ret))
else:
ret['message'] = '用户名或密码错误'
return HttpResponse(json.dumps(ret))
return render(request,'ajax_demo.html')

4.templates/ajax_demo.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>
<p>用户名:<input type="text" id="username" /></p>
</div>
<div>
<p>密码:<input type="password" id="pwd" /></p>
</div>
<input type="button" value="提交" onclick="SubmitForm();" /> <script src="/static/jquery-1.12.4.js"></script>
<script>
function SubmitForm() {
$.ajax({
url: '/web/ajax_demo/',
type: 'POST',
data: {'user': $('#username').val(), 'pwd': $('#pwd').val()},
//jQuery自动转换类型,无需自己转换
dataType: 'json',
success: function (data) {
//data字符串 {status:True, message:''}
//自己转换,没有使用jQuery的类型转换
//var data_dict = JSON.parse(data);
if (data.status) {
location.href = 'http://www.bing.com.cn';
}else {
alert(data.message);
}
}
})
}
</script>
</body>
</html>

四、Model

Model -- Django ORM
a、创建数据库表(CURD)
class -> DB,表
DB,表 -> 类
a、app.models.py写类
from django.db import models class userinfo(models.Model):
name = models.CharField(max_length=30) # string
email = models.EmailField() # string,帮助admin做输入验证
memo = models.TextField() # text b、python3 manage.py makemigrations
python3 manage.py migrate
b、操作数据库的数据 1、models.AutoField  自增列 = int(11)
  如果没有的话,默认会生成一个名称为 id 的列,如果要显示的自定义一个自增列,必须将给列设置为主键 primary_key=True。
2、models.CharField  字符串字段
  必须 max_length 参数
3、models.BooleanField  布尔类型=tinyint(1)
  不能为空,Blank=True
4、models.ComaSeparatedIntegerField  用逗号分割的数字=varchar
  继承CharField,所以必须 max_lenght 参数
5、models.DateField  日期类型 date
  对于参数,auto_now = True 则每次更新都会更新这个时间;auto_now_add 则只是第一次创建添加,之后的更新不再改变。
6、models.DateTimeField  日期类型 datetime
  同DateField的参数
7、models.Decimal  十进制小数类型 = decimal
  必须指定整数位max_digits和小数位decimal_places
8、models.EmailField  字符串类型(正则表达式邮箱) =varchar
  对字符串进行正则表达式
9、models.FloatField  浮点类型 = double
10、models.IntegerField  整形
11、models.BigIntegerField  长整形
  integer_field_ranges = {
    'SmallIntegerField': (-32768, 32767),
    'IntegerField': (-2147483648, 2147483647),
    'BigIntegerField': (-9223372036854775808, 9223372036854775807),
    'PositiveSmallIntegerField': (0, 32767),
    'PositiveIntegerField': (0, 2147483647),
  }
12、models.IPAddressField  字符串类型(ip4正则表达式)
13、models.GenericIPAddressField  字符串类型(ip4和ip6是可选的)
  参数protocol可以是:both、ipv4、ipv6
  验证时,会根据设置报错
14、models.NullBooleanField  允许为空的布尔类型
15、models.PositiveIntegerFiel  正Integer
16、models.PositiveSmallIntegerField  正smallInteger
17、models.SlugField  减号、下划线、字母、数字
18、models.SmallIntegerField  数字
  数据库中的字段有:tinyint、smallint、int、bigint
19、models.TextField  字符串=longtext
20、models.TimeField  时间 HH:MM[:ss[.uuuuuu]]
21、models.URLField  字符串,地址正则表达式
22、models.BinaryField  二进制
23、models.ImageField 图片 #字符串
24、models.FilePathField 文件 #字符串 c、连表结构
一对多:models.ForeignKey(其他表)
多对多:models.ManyToManyField(其他表)
一对一:models.OneToOneField(其他表)
obj = model.UserInfo.objects.filter(name='alex')
#打印SQL语句
print(obj)
quertset -> python, Django的类
[obj1,obj2,obj3,obj4,obj5] obj = model.UserInfo.objects.filter(name='alex').values('id','email')
[{'id':1,'email':11@qq.com},{'id':2',email':11@qq.com},{'id':3,'email':11@qq.com},{'id':4,'email':11@qq.com},] obj = model.UserInfo.objects.filter(name='alex').value_list('id','email')
[(1,'1.qq.com'),(2,'2.qq.com'),(3,'3.qq.com'),(4,'4.qq.com'),] e、了不起的双下划线
# 获取个数
#
# models.Tb1.objects.filter(name='seven').count() # 大于,小于
#
# models.Tb1.objects.filter(id__gt=1) # 获取id大于1的值
# models.Tb1.objects.filter(id__lt=10) # 获取id小于10的值
# models.Tb1.objects.filter(id__lt=10, id__gt=1) # 获取id大于1 且 小于10的值 # in
#
# models.Tb1.objects.filter(id__in=[11, 22, 33]) # 获取id等于11、22、33的数据
# models.Tb1.objects.exclude(id__in=[11, 22, 33]) # not in # contains
#
# models.Tb1.objects.filter(name__contains="ven")
# models.Tb1.objects.filter(name__icontains="ven") # icontains大小写不敏感
# models.Tb1.objects.exclude(name__icontains="ven") # range
#
# models.Tb1.objects.filter(id__range=[1, 2]) # 范围bettwen and # 其他类似
#
# startswith,istartswith, endswith, iendswith, # order by
#
# models.Tb1.objects.filter(name='seven').order_by('id') # asc
# models.Tb1.objects.filter(name='seven').order_by('-id') # desc # limit 、offset
#
# models.Tb1.objects.all()[10:20] # group by
from django.db.models import Count, Min, Max, Sum
# models.Tb1.objects.filter(c1=1).values('id').annotate(c=Count('num'))
# SELECT "app01_tb1"."id", COUNT("app01_tb1"."num") AS "c" FROM "app01_tb1" WHERE "app01_tb1"."c1" = 1 GROUP BY "app01_tb1"."id"

app01/models.py

from django.db import models

class UserType(models.Model):
name = models.CharField(max_length=32) def __str__(self):
return self.name class userinfo(models.Model):
nid = models.AutoField(primary_key=True)
# admin中字段显示名:verbose_name='用户名',数据库中的列名:db_column='u'
#是否可以被编辑:editable,error_message="用户名不能为空",help_text:admin中提示帮助信息
#
name = models.CharField(max_length=30, verbose_name='用户名')
email = models.EmailField()
memo = models.TextField()
#图片上传位置:upload_to
img = models.ImageField(upload_to='uoload')
# user_type字段可以为空null=True,Django中后台字段可以为空 blank=True,"UserType"加引号是为了新增的数据库表结构无论在上面还是在下面都可以执行
user_type = models.ForeignKey("UserType", null=True, blank=True) #unique
#普通用户
#超级用户
#user_type = models.OneToOneField("UserType", null=True, blank=True) #foreignkey + unique
#自动添加当前时间
# ctime = models.DateTimeField(auto_now_add=True)
# uptime = models.DateTimeField(auto_now=True) #对于固定值,直接写到内存中
gender_choices = (
(0, '男'),
(1, '女'),
)
gender = models.IntegerField(choices=gender_choices,default=1)
# 手工创建
"""
class B2G(models.Model):
boy = models.ForeignKey('Boy')
girl = models.ForeignKey('Girl')
"""
class Boy(models.Model):
name = models.CharField(max_length=32) class Girl(models.Model):
name = models.CharField(max_length=32)
#自动创建表,但是需要执行命令python3 manage.py makemigrations/python3 manage.py migrate
f = models.ManyToManyField(Boy)

day18/urls.py

from django.conf.urls import url
from django.contrib import admin
from django.conf.urls import url, include
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^web/', include('app01.urls')),
]

创建superuser用户

python manage.py createsuperuser

登录admin后台管理

http://127.0.0.1:8000/admin
上一篇:关于.netFramework概述


下一篇:angular学习(二)-- Directive