http://www.cnblogs.com/fnng/p/3737964.htmlhtml
引用自此博客python
建立blog的公共部分數據庫
從Django的角度看,django
一個頁面函數
具備三個典型的組件:url
一個模板(template):模板負責把傳遞進來的信息顯示出來。spa
一個視圖(view):視圖負責從數據庫獲取須要顯示的信息。code
一個URL模式:它負責把收到的請求和你的試圖函數匹配,有時候也會向視圖傳遞一些參數。htm
1.模板對象
2.視圖
3,建立一個URL模式
在mysite/urls.py,加上:url(r'^blog/', include('blog.urls')),
在blog/urls.py,加上: from django.conf.urls import * from blog.views import archive urlpatterns = patterns('', url(r'^$',archive), )
有報錯類:1:from django.conf.urls import *找不到patterns模塊? Django-1.10,python27
解決:這個特性在1.9就聲明瞭deprecated. 1.10正式移除了。使用 django 1.10 須要改用 django.conf.urls.url() 示範代碼:
意思就是改一下代碼的格式
from django.conf.urls import url from . import views urlpatterns = [ url(r'^articles/2003/$', views.special_case_2003), url(r'^articles/([0-9]{4})/$', views.year_archive), url(r'^articles/([0-9]{4})/([0-9]{2})/$', views.month_archive), url(r'^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$', views.article_detail), ]
遇到問題2:
TypeError at /blog/ context must be a dict rather than Context. Request Method: GET Request URL: http://127.0.0.1:8000/blog/ Django Version: 1.11 Exception Type: TypeError Exception Value: context must be a dict rather than Context. Exception Location: C:\Python27\lib\site-packages\django\template\context.py in make_context, line 287 Python Executable: C:\Python27\python.exe Python Version: 2.7.12 Python Path: ['C:\\Users\\yangyang5\\mysite', 'C:\\Windows\\system32\\python27.zip', 'C:\\Python27\\DLLs', 'C:\\Python27\\lib', 'C:\\Python27\\lib\\plat-win', 'C:\\Python27\\lib\\lib-tk', 'C:\\Python27', 'C:\\Python27\\lib\\site-packages', 'C:\\Python27\\lib\\site-packages\\wx-2.8-msw-unicode'] Server time: Mon, 10 Apr 2017 06:28:23 +0000
貌似是說views.py在調用get_temllate時有問題
解決辦法:換了種寫的方式
from django.shortcuts import render from django.shortcuts import render_to_response from django.template import loader,Context from django.http import HttpResponse from blog.models import BlogPost # Create your views here. def archive(request): blog_list=BlogPost.objects.all() return render_to_response('archive.html',{'blog_list':blog_list})
blog_list = BlogPost.objects.all() :獲取數據庫裏面所擁有BlogPost對象
render_to_response()返回一個頁面(index.html),順帶把數據庫中查詢出來的全部博客內容(blog_list)也一併返回。
最後的潤色
建立一個base.html,別的html均可以讓它引用base.html模板和它的「content」塊