request進來->從服務器獲取數(shù)據(jù)->處理數(shù)據(jù)->把網(wǎng)頁呈現(xiàn)出來
url設置相當于客戶端向服務器發(fā)出request請求的入口, 并用來指明要調用的程序邏輯views用來處理程序邏輯, 然后呈現(xiàn)到template(一般為GET方法, POST方法略有不同)template一般為html+CSS的形式, 主要是呈現(xiàn)給用戶的表現(xiàn)形式Django中views里面的代碼就是一個一個函數(shù)邏輯, 處理客戶端(瀏覽器)發(fā)送的HTTPRequest, 然后返回HTTPResponse,
那么那么開始在my_blog/article/views.py中編寫簡單的邏輯
#現(xiàn)在你的views.py應該是這樣
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def home(request):
return HttpResponse("Hello World, Django")
那么如何使這個邏輯在http請求進入時, 被調用呢, 這里需要在my_blog/my_blog/urls.py中進行url設置
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'my_blog.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^$', 'article.views.home'), #由于目前只有一個app, 方便起見, 就不設置include了
)
url()函數(shù)有四個參數(shù), 兩個是必須的:regex和view, 兩個可選的:kwargs和name
regex是regular expression的簡寫,這是字符串中的模式匹配的一種語法, Django 將請求的URL從上至下依次匹配列表中的正則表達式,直到匹配到一個為止。更多正則表達式的使用可以查看Python正則表達式
view當 Django匹配了一個正則表達式就會調用指定的view邏輯, 上面代碼中會調用article/views.py中的home函數(shù)kwargs任意關鍵字參數(shù)可傳一個字典至目標viewname命名你的 URL, 使url在 Django 的其他地方使用, 特別是在模板中現(xiàn)在在瀏覽器中輸入127.0.0.1:8000應該可以看到下面的界面
http://wiki.jikexueyuan.com/project/django-set-up-blog/images/64.png" alt="成功" />
很多時候我們希望給view中的函數(shù)邏輯傳入?yún)?shù), 從而呈現(xiàn)我們想要的結果
現(xiàn)在我們這樣做, 在my_blog/article/views.py加入如下代碼:
def detail(request, my_args):
return HttpResponse("You're looking at my_args %s." % my_args)
在my_blog/my_blog/urls.py中設置對應的url,
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'my_blog.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^$', 'article.views.home'),
url(r'^(?Pd+)/$', 'article.views.detail', name='detail'),
)
^(?Pd+)/$這個正則表達式的意思是將傳入的一位或者多位數(shù)字作為參數(shù)傳遞到views中的detail作為參數(shù), 其中?P定義名稱用于標識匹配的內容
一下url都能成功匹配這個正則表達數(shù)
http://127.0.0.1:8000/1000/http://127.0.0.1:8000/9/嘗試傳參訪問數(shù)據(jù)庫
修改在my_blog/article/views.py代碼:
from django.shortcuts import render
from django.http import HttpResponse
from article.models import Article
# Create your views here.
def home(request):
return HttpResponse("Hello World, Django")
def detail(request, my_args):
post = Article.objects.all()[int(my_args)]
str = ("title = %s, category = %s, date_time = %s, content = %s"
% (post.title, post.category, post.date_time, post.content))
return HttpResponse(str)
這里最好在admin后臺管理界面增加幾個Article對象, 防止查詢對象為空, 出現(xiàn)異常
現(xiàn)在可以訪問http://127.0.0.1:8000/1/
顯示如下數(shù)據(jù)表示數(shù)據(jù)庫訪問正確(這些數(shù)據(jù)都是自己添加的), 并且注意Article.objects.all()返回的是一個列表
http://wiki.jikexueyuan.com/project/django-set-up-blog/images/65.png" alt="數(shù)據(jù)" />
小結: