由於django是在快節奏的編輯環境下開發的,它旨在使常見的Web開發任務變得快速而簡單。 這是一個關於如何用django編寫數據庫驅動的Web應用程序的非正式概述。php
本文檔的目的是爲您提供足夠的技術細節來了解django的工做原理,但這不是一個教程或參考 - 可是咱們已經有了! 當您準備開始一個項目時,您能夠從教程開始,或者直接進入更詳細的文檔。html
儘管您能夠在沒有數據庫的狀況下使用django,但它附帶一個對象關係映射器,您能夠在其中以python代碼描述數據庫佈局。python
數據模型語法提供了許多豐富的表明模型的方法 - 到目前爲止,它一直在解決多年的數據庫模式問題。 這是一個快速的例子:程序員
mysite/news/models.py
正則表達式
from django.db import models class Reporter(models.Model): full_name = models.CharField(max_length=70) def __str__(self): # __unicode__ on Python 2 即爲在python2的語法中此處應該爲def __unicode__(self): return self.full_name class Article(models.Model): pub_date = models.DateField() headline = models.CharField(max_length=200) content = models.TextField() reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) def __str__(self): # __unicode__ on Python 2 return self.headline
接下來,運行django命令行實用程序自動建立數據庫表:數據庫
$ python manage.py migrate
其實在高版本的django中建立數據庫表的完整步驟應該是,首先在命令窗口進入到項目文件的目錄下有manage.py的那一層,前後運行:django
python manage.py makemigrations # 生成數據庫遷移文件 python manage.py migrate # 建立數據庫表
migrate命令查看全部可用的模型,並在數據庫中建立不存在的表以及可選地提供更豐富的模式控制的表。後端
所以,您有一個免費且豐富的Python API來訪問您的數據。 API是即時建立的,不須要代碼生成:緩存
# Import the models we created from our "news" app >>> from news.models import Reporter, Article # No reporters are in the system yet. >>> Reporter.objects.all() <QuerySet []> # Create a new Reporter. >>> r = Reporter(full_name='John Smith') # Save the object into the database. You have to call save() explicitly. >>> r.save() # Now it has an ID. >>> r.id 1 # Now the new reporter is in the database. >>> Reporter.objects.all() <QuerySet [<Reporter: John Smith>]> # Fields are represented as attributes on the Python object. >>> r.full_name 'John Smith' # Django provides a rich database lookup API. >>> Reporter.objects.get(id=1) <Reporter: John Smith> >>> Reporter.objects.get(full_name__startswith='John') <Reporter: John Smith> >>> Reporter.objects.get(full_name__contains='mith') <Reporter: John Smith> >>> Reporter.objects.get(id=2) Traceback (most recent call last): ... DoesNotExist: Reporter matching query does not exist. # Create an article. >>> from datetime import date >>> a = Article(pub_date=date.today(), headline='Django is cool', ... content='Yeah.', reporter=r) >>> a.save() # Now the article is in the database. >>> Article.objects.all() <QuerySet [<Article: Django is cool>]> # Article objects get API access to related Reporter objects. >>> r = a.reporter >>> r.full_name 'John Smith' # And vice versa: Reporter objects get API access to Article objects. 外鍵反向查詢 >>> r.article_set.all() <QuerySet [<Article: Django is cool>]> # The API follows relationships as far as you need, performing efficient # JOINs for you behind the scenes. # This finds all articles by a reporter whose name starts with "John". >>> Article.objects.filter(reporter__full_name__startswith='John') <QuerySet [<Article: Django is cool>]> # Change an object by altering its attributes and calling save(). >>> r.full_name = 'Billy Goat' >>> r.save() # Delete an object with delete(). >>> r.delete()
一旦您的模型被定義,Django能夠自動建立一個專業的,生產就緒的管理界面 - 容許通過身份驗證的用戶添加,更改和刪除對象的網站。 在管理員網站上註冊您的模型很是簡單:app
mysite/news/models.py
from django.db import models class Article(models.Model): pub_date = models.DateField() headline = models.CharField(max_length=200) content = models.TextField() reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)
mysite/news/admin.py
from django.contrib import admin from . import models admin.site.register(models.Article)
這裏的理念是,您的網站由員工或客戶端編輯,也可能僅僅是您編輯 - 而您不須要處理建立後端接口來管理內容。
建立django應用程序的一個典型工做流程是建立模型並儘量快地讓管理站點運行起來,所以您的員工(或客戶端)能夠開始填充數據。 而後,開發數據呈現給公衆的方式。
一個乾淨,優雅的URL方案是高質量Web應用程序中的重要細節。 django鼓勵漂亮的網址設計,並不會在URL中放置其餘的東西,好比 .php 或 .asp 。
要設計應用程序的URL,您能夠建立一個名爲URLconf的python模塊。 您的應用程序的目錄,它包含URL模式和python回調函數之間的簡單映射。 URLconfs還用於將URL與python代碼分離。
如下是關於上面的 Reporter/Article 示例中的URLconf的內容:
mysite/news/urls.py
from django.conf.urls import url from . import views urlpatterns = [ 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), ]
上面的代碼將URL做爲簡單的正則表達式映射到python回調函數("views")的位置。 正則表達式使用括號來從URL"捕獲"值。 當用戶請求頁面時,django按順序運行每一個模式,並在與所請求的URL匹配的第一個模式下中止。(若是沒有匹配,Django會調用特殊狀況的404視圖。)這是很是快的,由於正則表達式是在加載時編譯的。
一旦正則表達式匹配,django會調用給定的視圖,這是一個python函數。每一個視圖都會傳遞一個請求對象(包含請求元數據)以及在正則表達式中捕獲的值。
例如,若是用戶請求URL "/articles/2005/05/39323/",django將調用函數
news.views.article_detail(request, '2005', '05', '39323')。
每一個視圖都負責執行如下兩項操做之一:返回包含所請求頁面內容的HttpResponse對象,或引起異常(如Http404)。其他的取決於你。
一般,視圖根據參數檢索數據,加載模板並使用檢索到的數據呈現模板。如下是上述year_archive的示例視圖:
mysite/news/views.py
from django.shortcuts import render from .models import Article def year_archive(request, year): a_list = Article.objects.filter(pub_date__year=year) context = {'year': year, 'article_list': a_list} return render(request, 'news/year_archive.html', context)
該示例使用django的模板系統,它具備幾個強大的功能,但努力保持足夠簡單以便非程序員使用。
上面的代碼加載了 news/year_archive.html 模板。
django具備模板搜索路徑,能夠最大程度地減小模板之間的冗餘。在django設置中,您能夠指定使用DIRS檢查模板的目錄列表。若是第一個目錄中不存在模板,則會檢查第二個目錄,依此類推。
假設發現 news/year_archive.html 模板。這多是這樣的:
mysite/news/templates/news/year_archive.html
{% extends "base.html" %} {% block title %}Articles for {{ year }}{% endblock %} {% block content %} <h1>Articles for {{ year }}</h1> {% for article in article_list %} <p>{{ article.headline }}</p> <p>By {{ article.reporter.full_name }}</p> <p>Published {{ article.pub_date|date:"F j, Y" }}</p> {% endfor %} {% endblock %}
變量被雙花括號包圍。 {{article.headline}} 表示"輸出文章headline屬性的值",可是點不只僅用於屬性查找。他們還能夠進行字典鍵查找,索引查找和函數調用。
注意 {{article.pub_date | date:"F j,Y"}} 使用Unix風格的"pipe"("|"字符)。這被稱爲模板過濾器,它是一種過濾變量值的方法。在這種狀況下,日期過濾器會以給定的格式(一樣能夠在PHP的日期函數中找到)格式化python datetime對象。
您能夠將所需的過濾器連接在一塊兒。您能夠編寫自定義模板過濾器。您能夠編寫自定義模板標籤,該標籤在幕後運行自定義的python代碼。
最後,django使用"模板繼承"的概念。這就是 {% extends "base.html" %} 。這意味着"首先加載名爲'base'的模板,它定義了一堆塊,並使用如下塊填充塊。"簡而言之,這樣能夠大大減小模板中的冗餘:每一個模板只能定義該模板有什麼獨特之處。
如下是"base.html"模板,包括使用靜態文件,可能以下所示:
mysite/templates/base.html
{% load static %} <html> <head> <title>{% block title %}{% endblock %}</title> </head> <body> <img src="{% static "images/sitelogo.png" %}" alt="Logo" /> {% block content %}{% endblock %} </body> </html>
簡單來講,它定義了網站的外觀(與網站的徽標),併爲子模板填充提供了"洞"。 這使得站點從新設計與更改單個文件(基本模板)同樣簡單。
它還容許您建立多個版本的站點,具備不一樣的基本模板,同時重用子模板。django的創做者已經使用這種技術來建立驚人的不一樣的移動版本的網站 - 只需建立一個新的基本模板。
請注意,若是您喜歡其餘系統,則沒必要使用django的模板系統。雖然django的模板系統與django的模型層特別完美地結合在一塊兒,可是沒有什麼會強制你使用它。爲此,您沒必要使用django的數據庫API。您可使用另外一個數據庫抽象層,您能夠讀取XML文件,您能夠從磁盤讀取文件,或任何您想要的內容。每一個django - 模型,視圖,模板 - 與下一個分離。
這只是Django功能的簡要概述。 一些更有用的功能:
與memcached或其餘後端集成的緩存框架。一個聯合框架,使得建立RSS和Atom feed與編寫一個小python類同樣簡單。更性感自動生成的管理功能 - 這個概述幾乎沒有觸及表面。下一個明顯的步驟是爲您下載django,閱讀教程並加入社區。 感謝您的關注!