1.创建Django工程

django-admin startproject 工程名

2.创建app

cd 工程名

python manage.py startapp cmdb

3.静态文件

project.settings.py

  1. STATICFILES_DIRS = (  
  2. 'static'),  
  3.     )  

4.模板路径

  1. TEMPLATE_DIRS = (  
  2. 'templates'),  
  3.     )  

5.settings中

middlerware  #注释 csrf

6.定义路由规则(路由系统URL)

(1) url(r'^index/',views.index),

(2)url(r'^home/',views.Home.as_view()),

(3)url(r'^detail-(\d+).html',views.detail),   

    def detail(request,nid):

(4) url(r'^index-(\d+nid)-(\d+uid).html/',views.index),

def index(request,nid,uid)#一一对应

(5)url(r'^index/(?P<nid>\d+/(?P<uid>\d+)/',views.index),


def index(request,*args,**kwargs):  #分别对应args--nid和kwargs--uid


(6)name:对url路由关系进行命名,以后可以根据此名称生成自己想要的url

url(r'^abc/',views.index,name='index1',)--->对应模板语言 {%url "index1"%}

url(r'^abc/(\d+)/',views.index,name="index1")-->对应模板语言{%url "index1" 3%}  #生成固定


注:

html表单里面的action :{{request.path_info}}

(7)name

from django.utls import reverse

reverse('indexs',args=(90,))或reverse('indexs',kwargs={"nid":1,"uid":2})

eg:

url(r'^abc/',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') #abc/

url2 = reverse('i2',args=(1,2))  #yug/1/2/

url3 = reverse('i3',kwarge={'pid':1,'nid':2}) #buy/1/9/


xxx.html

{%url "i1%" }   #abc/

{%url "i2 1 2%" }  #yug/1/2

{%url "i3" pid=1 nid=9 %}  #buy/1/9/

(8)路由分发:多个app时

url(r^'app01/',include("app01.urls")),

url(r^'app02/',include("app02.urls")),

(9)默认值

(10)命名空间

7.定义视图函数

app下views.py

获取数据:

def fun(request):
     #request.method  GET/POST
    #http://127.0.0.1:8009/home?nid=123&name=julia
    #request.GET.get('',None)  获取请求发来的数据
    #request.POST.get('',None)

返回数据:

#return HttpResponse('字符串')
    #return render(requets,'HTML模板的路径',{‘ ’})
    #return redirect('/只能填url')  #只能传url前面的路径,不能直接传模板

补充:

request.GET
request.POST
request.FILES  #获取文件请求
request.POST.getlist()   #获取checkbox等多选的内容
#上传文件

form里面必须设置: enctype=“multipart/form-data”

obj = request.FILES.get('文件名')
obj.name
f =open(obj.name,mode='wb')
for item in obj.chunks():
    f.write(item)
f.close()

函数vs类:

FBV&CBV
function base view
url.py
    index-->函数名
view.py
    def 函数(request):
==>
/index/ -->函数名
/index/ --> 类 (基层views)

建议连着都用

8.模板渲染

特殊的模板语言

{{变量名}}

def func(request):

    return render(request,"index.html",{'current_user':"julia"})

index.html

<html>

..

<body>

    <div>{{current_user}}</div>

</body>

</html>

==>最后生成

<html>

..

<body>

    <div>julia</div>

</body>

</html>

--for循环、if、

def func(request):

    return render(request,"index.html",{'current_user':"julia",'user_list':['alex','eric'],'user_dict':{'k1':'v1','k2':'v2'}})

index.html

...

{% for row in user_list%}

    <li>{{row}}</li>

{%endfor%}

<a>{{user_list.1}}</a>

<a>{{user_dict.k1}}</a>