文檔
中文1.8 :
http://python.usyiyi.cn/django/index.html
英文1.10:
https://docs.djangoproject.com/en/1.10/
setting:
https://docs.djangoproject.com/en/1.9/ref/settings/#databases
基本命令
創(chuàng)建項目
django-admin.py startproject mysite
創(chuàng)建app
python manage.py startapp books
添加app到setting后運行命令
python manage.py makemigrations appname
使用現(xiàn)有的數(shù)據(jù)庫
python manage.py inspectdb
django會根據(jù)配置的數(shù)據(jù)庫中的表生成models語句
python manage.py inspectdb > models.py
查看模型對應的sql語句
python manage.py sqlmigrate appname
install the core Django tables
python manage.py migrate
啟動
python manage.py runserver
更改運行端口
python manage.py runserver 8080
局域網(wǎng)訪問
python manage.py runserver 0.0.0.0:8080
視圖 The view layer
url配置
url傳遞參數(shù)給視圖
命名正則表達式組的語法是(?P<name>pattern)
,其中name
是組的名稱记罚,pattern
是匹配模式契沫。
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^articles/2003/$', views.special_case_2003),
url(r'^articles/(?P<year>[0-9]{4})/$', views.year_archive),
url(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$', views.month_archive),
url(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/(?P<day>[0-9]{2})/$', views.article_detail),
]
# /articles/2005/03/ 請求將調(diào)用views.month_archive(request, year='2005', month='03')函數(shù)受楼,而不是views.month_archive(request, '2005', '03')摸航。
指定視圖參數(shù)默認值
# URLconf
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^blog/$', views.page),
url(r'^blog/page(?P<num>[0-9]+)/$', views.page),
]
# View (in blog/views.py)
def page(request, num="1"):
# Output the appropriate page of blog entries, according to num.
...
在上面的例子中,兩個URL模式指向同一個視圖views.page —— 但是第一個模式不會從URL 中捕獲任何值担锤。如果第一個模式匹配不翩,page() 函數(shù)將使用num參數(shù)的默認值"1"齿诞。如果第二個模式匹配衡便,page() 將使用正則表達式捕獲的num 值献起。
獲取url的querystring和設置默認值
#一般方法
if 'date' in request.GET:
date = request.GET['date']
else:
date = '2010-05-04'
#簡寫方法
data = request.GET.get('data','2010-05-04')
批量301 302
# 302
from django import http
def view(request):
return http.HttpResponseRedirect('http://example.cn/')
#301
from django import http
def view(request):
return http.HttpResponsePermanentRedirect('http://example.cn/')