1、Django请求生命周期
两种情况:最终返回的是字符串
1、-> URL对应关系(匹配) -> 视图函数 -> 返回用户字符串
2、-> URL对应关系(匹配) -> 视图函数 -> 打开一个HTML文件,读取内容
2、创建django projcet

django-admin startproject mysite

mysite
mysite
- 配置文件
- url.py
- settings.py

cd mysite
python manage.py startapp cmdb

mysite
mysite
- 配置文件
- url.py
- settings.py
cmdb
- views.py
- admin.py
- models.py # 创建数据库表

3、配置

模板路径
静态文件路径
# CSRF 注释掉

4、编写程序

a. url.py

/index/ -> func

b. views.py

def func(request):
# 包含所有的请求数据
...
获取字符串: return HttpResponse('字符串')
获取html: return render(request, 'index.html', {''})
获取url: retrun redirect('URL')

c. 模板语言
return render(request, 'index.html', {'li': [11,22,33]})
for循环获取数据
{% for item in li %}
<h1>{{item}}</h1>
{% endfor %}

*********** 索引用点 **********获取第一个数据
<h2> {{item.0 }} </h2>
一、路由系统,URL。py文件里面有数据
1、url(r'^index/', views.index),
url(r'^home/', views.Home.as_view()),
2、url(r'^detail-(\d+).html', views.detail),
3、url(r'^detail-(?P<nid>\d+)-(?P<uid>\d+).html', views.detail)

PS:
def detail(request, *args,**kwargs):
pass

实战:
a.
url(r'^detail-(\d+)-(\d+).html', views.detail),

def func(request, nid, uid):
pass

def func(request, *args):
args = (2,9)


def func(request, *args, **kwargs):
args = (2,9)

b.
url(r'^detail-(?P<nid>\d+)-(?P<uid>\d+).html', views.detail)

def func(request, nid, uid):
pass

def funct(request, **kwargs):
kwargs = {'nid': 1, 'uid': 3}

def func(request, *args, **kwargs):
args = (2,9)
4、 name

对URL路由关系进行命名, ***** 以后可以根据此名称生成自己想要的URL *****

url(r'^asdfasdfasdf/', views.index, name='i1'),
url(r'^yug/(\d+)/(\d+)/', views.index, name='i2'),
url(r'^buy/(?P<pid>\d+)/(?P<nid>\d+)/', views.index, name='i3'),



def func(request, *args, **kwargs):
from django.urls import reverse

url1 = reverse('i1') # asdfasdfasdf/
url2 = reverse('i2', args=(1,2,)) # yug/1/2/
url3 = reverse('i3', kwargs={'pid': 1, "nid": 9}) # buy/1/9/


xxx.html

{% url "i1" %} # asdfasdfasdf/
{% url "i2" 1 2 %} # yug/1/2/
{% url "i3" pid=1 nid=9 %} # buy/1/9/

注:
# 当前的URL
request.path_info
5、多级路由

project/urls.py
from django.conf.urls import url,include
from django.contrib import admin

urlpatterns = [
url(r'^cmdb/', include("app01.urls")),
url(r'^monitor/', include("app02.urls")),
]

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


from django.conf.urls import url,include
from django.contrib import admin
from app01 import views

urlpatterns = [
url(r'^login/', views.login),
url(r'^index/', views.index),
url(r'^user_info/', views.user_info),
url(r'^userdetail-(?P<nid>\d+)/', views.user_detail),
url(r'^userdel-(?P<nid>\d+)/', views.user_del),
url(r'^useredit-(?P<nid>\d+)/', views.user_edit),
url(r'^orm/', views.orm),
]
from django.shortcuts import render,HttpResponse,redirect

def login(request):
if request.method == "GET":
return render(request, 'login.html')
elif request.method == "POST":
# 数据库中执行 select * from user where usernam='x' and password='x'
u = request.POST.get('user')
p = request.POST.get('pwd')
# obj = models.UserInfo.objects.filter(username=u,password=p).first()
# print(obj)# obj None,
# count = models.UserInfo.objects.filter(username=u, password=p).count()
obj = models.UserInfo.objects.filter(username=u, password=p).first()
if obj:
return redirect('/cmdb/index/')
else:
return render(request, 'login.html')
else:
# PUT,DELETE,HEAD,OPTION...
return redirect('/index/')


def index(request):
return render(request, 'index.html')

def user_info(request):
if request.method == "GET":
user_list = models.UserInfo.objects.all()
# print(user_list.query)
# QuerySet [obj,obj,]
return render(request, 'user_info.html', {'user_list': user_list})
elif request.method == 'POST':
u = request.POST.get('user')
p = request.POST.get('pwd')
models.UserInfo.objects.create(username=u,password=p)
return redirect('/cmdb/user_info/')
# user_list = models.UserInfo.objects.all()
# return render(request, 'user_info.html', {'user_list': user_list})

def user_detail(request, nid):
obj = models.UserInfo.objects.filter(id=nid).first()
# 去单挑数据,如果不存在,直接报错
# models.UserInfo.objects.get(id=nid)
return render(request, 'user_detail.html', {'obj': obj})

def user_del(request, nid):
models.UserInfo.objects.filter(id=nid).delete()
return redirect('/cmdb/user_info/')

def user_edit(request, nid):
if request.method == "GET":
obj = models.UserInfo.objects.filter(id=nid).first()
return render(request, 'user_edit.html',{'obj': obj})
elif request.method == "POST":
nid = request.POST.get('id')
u = request.POST.get('username')
p = request.POST.get('password')
models.UserInfo.objects.filter(id=nid).update(username=u,password=p)
return redirect('/cmdb/user_info/')
from django.db import models

# Create your models here.
# app01_userinfo
class UserInfo(models.Model):
# id列,自增,主键
# 用户名列,字符串类型,指定长度
username = models.CharField(max_length=32)
password = models.CharField(max_length=64)

 

django里面的增加 删除 修改,查询:

from app01 import models
def orm(request):
# 创建
#一般用他: # models.UserInfo.objects.create(username='root',password='123')

# dic = {'username': 'eric', 'password': '666'}
# models.UserInfo.objects.create(**dic)

# obj = models.UserInfo(username='alex',password='123')
# obj.save()

# 查
# result = models.UserInfo.objects.all()
# result = models.UserInfo.objects.filter(username='root',password='123')
#
# result,QuerySet => Django => []
# [obj(id,username,password),obj(id,username,password), obj(id,username,password)]
# for row in result:
# print(row.id,row.username,row.password)
# print(result)

# 删除
# models.UserInfo.objects.filter(username="alex").delete()

# 更新
# models.UserInfo.objects.filter(id=3).update(password="69")

return HttpResponse('orm')

 

django 1.8之后推出的migrations机制使django的数据模式管理更方便容易,现在简单谈谈他的机制和一些问题的解决方法:

1、谈谈机制:migrations机制有两个指令,第一个是makemigrations,

第二个是migrate,生成migrations代码的makemigrations指令是用models里面的model和当前的migrations代码里面的model做对比,

如果有新的修改,就生成新的migrations代码,

migrate指令是用migrations目录中代码文件和django​​数据库​​djaong_migrations表中的代码文件做对比,

如果表中没有,那就对这些没有的文件按顺序及依赖关系做migrate apply,然后再把代码文件名加进migrations表中

一些问题的解决方法:

1、旧的项目如果升级到migrations机制:项目当前状态,应该是数据库和model定义一致,然后makemigtations,把生成的migrations initial文件全部加进django_migtrations表中,剩下的工作就和正常使用一样了。

2、managed=Fasle表的​​测试​​处理,空库测试,这部分表也需要做进测试数据库,这部分表,可以先在False状态下makemigrations,然后migrate一次,这样那些migrations代码已经属于已执行状态,剩下的就是把model和migrations代码中的manged全部切为true,这样这些代码就可以在空库测试中可用,同时不会再向数据库同步,当然这些表加字段就需要你自己先makemigrations一次,然后手动merge新旧migratons脚本,当然最后最后这部分新的migrations代码需要删除掉。

3、关于migrations Schema学习的问题,migrations代码实际叫Schema,这个代码也是​​Python​​代码,非常易读,稍微学一下,以后可以帮助你解决不少类似问题2这样的问题

 

 


心有猛虎,细嗅蔷薇