-
Django at a glance?
django 總覽
-
Because Django was developed in a fast-paced newsroom environment, it was designed to make common Web-development tasks fast and easy. Here’s an informal overview of how to write a database-driven Web app with Django.
django是在一個快節(jié)奏的新聞環(huán)境下誕生的, 所以它的目的是使普通的web開發(fā)任務(wù)快速且容易. 以下關(guān)于如何編寫一個數(shù)據(jù)庫驅(qū)動的django-web程序, 是非正式的.
-
The goal of this document is to give you enough technical specifics to understand how Django works, but this isn’t intended to be a tutorial or reference – but we’ve got both! When you’re ready to start a project, you can start with the tutorial or dive right into more detailed documentation.
本文的目的是給予足夠多的細節(jié)讓你明白django是如何工作的. 但這并不意味著這就是教程或者參考—— 我們已經(jīng)有教程和參考了. 當你準備開始一個項目時, 可以直接從教程開始, 也可以進入更詳細的文檔中去
-
Design your model?
設(shè)計你的模型
-
Although you can use Django without a database, it comes with an object-relational mapper in which you describe your database layout in Python code.
雖然你可能在用django時不會使用數(shù)據(jù)庫, 但他所具備的對象關(guān)系映射功能, 能夠讓我們用python代碼來創(chuàng)建或者使用數(shù)據(jù)庫.
-
The data-model syntax offers many rich ways of representing your models – so far, it’s been solving many years’ worth of database-schema problems. Here’s a quick example:
數(shù)據(jù)模型語法提供了豐富的方法來表示你的模型. 到現(xiàn)在為止, 它已經(jīng)解決了多年的數(shù)據(jù)庫模式問題. 下面是一個快速的例子:
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
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
-
Install it?
安裝
-
Next, run the Django command-line utility to create the database tables automatically:
接著, 通過命令到數(shù)據(jù)庫中創(chuàng)建表.
$ python manage.py migrate
-
The migrate command looks at all your available models and creates tables in your database for whichever tables don’t already exist, as well as optionally providing much richer schema control.
遷移命令查看所有可用的模型, 并創(chuàng)建那些在數(shù)據(jù)庫中尚不存在的表, 也提供豐富的模式控制.
-
Enjoy the free API?
盡情享受免費的接口
-
With that, you’ve got a free, and rich, Python API to access your data. The API is created on the fly, no code generation necessary:
到目前為止,已經(jīng)有免費且豐富的接口來訪問數(shù)據(jù)庫.這些接口時的創(chuàng)建, 不需要額外的代碼.
# Import the models we created from our "news" app
# 從app news 中導入 model
>>> from news.models import Reporter, Article
# No reporters are in the system yet.
# 目前數(shù)據(jù)中還沒有內(nèi)容
>>> Reporter.objects.all()
<QuerySet []>
# Create a new Reporter.
# 創(chuàng)建一條記錄
>>> r = Reporter(full_name='John Smith')
# Save the object into the database. You have to call save() explicitly.
# 保存對象到數(shù)據(jù)庫. 必須call save() .
>>> r.save()
# Now it has an ID.
# 現(xiàn)在就有了ID.
>>> r.id
1
# Now the new reporter is in the database.
# 數(shù)據(jù)庫中已經(jīng)有了內(nèi)容
>>> 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.
# django 提供了一個豐富的查詢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.
# 創(chuàng)建的數(shù)據(jù)到數(shù)據(jù)庫中去了
>>> 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.
# 另外一種關(guān)于外鍵的使用,
>>> 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()
-
A dynamic admin interface: it’s not just scaffolding – it’s the whole house?
一個動態(tài)的管理界面: 他只是架子, 而是整個房子.
-
Once your models are defined, Django can automatically create a professional, production ready administrative interface – a website that lets authenticated users add, change and delete objects. It’s as easy as registering your model in the admin site:
一旦定義了你的模型, django可以自動創(chuàng)建一個專業(yè)的, 生產(chǎn)準備的管理界面, 可以對用戶進行添加, 更改, 刪除.
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)
-
The philosophy here is that your site is edited by a staff, or a client, or maybe just you – and you don’t want to have to deal with creating backend interfaces just to manage content.
這里的理念是, 你的站點由一個人編寫, 同時你不想為了管理內(nèi)容添加后端接口.
-
One typical workflow in creating Django apps is to create models and get the admin sites up and running as fast as possible, so your staff (or clients) can start populating data. Then, develop the way data is presented to the public.
django中的典型工作流程是, 為了創(chuàng)建model 去創(chuàng)建apps , 然后盡快把相關(guān)表注冊到管理界面, 然后運行, 最后是開發(fā)可以面向公眾的頁面或者接口.
-
Design your URLs?
設(shè)計你的url.
-
A clean, elegant URL scheme is an important detail in a high-quality Web application. Django encourages beautiful URL design and doesn’t put any cruft in URLs, like .php or .asp.
干凈, 優(yōu)雅的url方案是高質(zhì)量web應(yīng)用程序的重要環(huán)節(jié), django鼓勵設(shè)計漂亮的url, 但是不放任何不整齊或討人厭的東西在url中,比如 php, asp
-
To design URLs for an app, you create a Python module called a URLconf. A table of contents for your app, it contains a simple mapping between URL patterns and Python callback functions. URLconfs also serve to decouple URLs from Python code.
為了給一個app設(shè)計urls, 你可以創(chuàng)建一個叫做URLconf 的模塊, 它需要配置你app中url和url 函數(shù)的對應(yīng)關(guān)系, 作為映射.
-
Here’s what a URLconf might look like for the Reporter/Article example above:
這里有個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),
]
-
The code above maps URLs, as simple regular expressions, to the location of Python callback functions (“views”). The regular expressions use parenthesis to “capture” values from the URLs. When a user requests a page, Django runs through each pattern, in order, and stops at the first one that matches the requested URL. (If none of them matches, Django calls a special-case 404 view.) This is blazingly fast, because the regular expressions are compiled at load time.
上面的代碼, 將url作為簡單的正則表達式映射到python回調(diào)函數(shù), 也就是view中, 正則表達式使用括號從url中捕獲值, 當用戶請求一個頁面時, django貫穿所有的url, 停在第一個匹配的url中. 正則表達式在加載時編譯, 所以速度會很快.
-
Once one of the regexes matches, Django calls the given view, which is a Python function. Each view gets passed a request object – which contains request metadata – and the values captured in the regex.
一旦匹配上了給定的視圖, 每個視圖函數(shù)傳入的參數(shù)為請求對象request 和 正則表達式中捕獲的值.
-
For example, if a user requested the URL “/articles/2005/05/39323/”, Django would call the function news.views.article_detail(request, '2005', '05', '39323').
比如, url /articles/2005/05/39323/ 將匹配 views.article_detail, 同時傳入的參數(shù)為(request,'2005','05','39923')
-
Write your views?
編寫你的視圖
-
Each view is responsible for doing one of two things: Returning an HttpResponse object containing the content for the requested page, or raising an exception such as Http404. The rest is up to you.
每個視圖做兩件事兒: 返回HttpResponse對象或者一個異常, 比如 Http404.
-
Generally, a view retrieves data according to the parameters, loads a template and renders the template with the retrieved data. Here’s an example view for year_archive from above:
一般來說, 視圖根據(jù)參數(shù)檢索數(shù)據(jù), 使用檢索后的數(shù)據(jù)加載模板. 比如:
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)
-
This example uses Django’s template system, which has several powerful features but strives to stay simple enough for non-programmers to use.
上面的這個例子使用了django的模板系統(tǒng),功能強大, 對非程序員來說也足夠簡單.
-
Design your templates?
設(shè)計你的模板
-
The code above loads the news/year_archive.html template.
上面的代碼導入了 模板 news/year_archive.html.
-
Django has a template search path, which allows you to minimize redundancy among templates. In your Django settings, you specify a list of directories to check for templates with DIRS. If a template doesn’t exist in the first directory, it checks the second, and so on.
django 中有一個模板搜索路徑, 我們要盡量的減少多余的模板. 我們在項目中的settings中, 也可以指定一個模板路徑. 如果第一個目錄中不存在該模板, 就會依次往后檢查.
-
Let’s say the news/year_archive.html template was found. Here’s what that might look like:
模板的內(nèi)容:
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 %}
-
Variables are surrounded by double-curly braces. {{ article.headline }} means “Output the value of the article’s headline attribute.” But dots aren’t used only for attribute lookup. They also can do dictionary-key lookup, index lookup and function calls.
變量被雙括號包圍. {{ article.headline }} 代表輸出article的headline屬性. 當然, 還可以用于字典鍵, 索引, 和函數(shù)調(diào)用.
-
Note {{ article.pub_date|date:"F j, Y" }} uses a Unix-style “pipe” (the “|” character). This is called a template filter, and it’s a way to filter the value of a variable. In this case, the date filter formats a Python datetime object in the given format (as found in PHP’s date function).
{{ article.pub_date|date:"F j, Y" }} 使用了UNIX 中的管道風格. 這被稱作模板篩選器, 他是過濾變量的一種方式. 此處, 將會篩選固定格式的DateTime對象.
-
You can chain together as many filters as you’d like. You can write custom template filters. You can write custom template tags, which run custom Python code behind the scenes.
你可以像你想的那樣, 將多個過濾器鏈接起來. 也可以編寫自己的模板過濾器, 可以編寫自定義的模板標記, 在后臺運行自定義python代碼.
-
Finally, Django uses the concept of “template inheritance”. That’s what the {% extends "base.html" %} does. It means “First load the template called ‘base’, which has defined a bunch of blocks, and fill the blocks with the following blocks.” In short, that lets you dramatically cut down on redundancy in templates: each template has to define only what’s unique to that template.
最后, django有模板繼承的概念, 在{% extends "base.html" %}處. 它首先加載這個模板, 然后用下面的內(nèi)容填充加載的模板中的塊. 能夠減少模板的冗余.
-
Here’s what the “base.html” template, including the use of static files, might look like:
base.html 中代碼. 包含了靜態(tài)文件的使用.
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>
-
Simplistically, it defines the look-and-feel of the site (with the site’s logo), and provides “holes” for child templates to fill. This makes a site redesign as easy as changing a single file – the base template.
簡單來說, 它定義了網(wǎng)站的外觀和感覺(和網(wǎng)站logo), 多種技術(shù)使得網(wǎng)站重新設(shè)計變得很簡單.
-
It also lets you create multiple versions of a site, with different base templates, while reusing child templates. Django’s creators have used this technique to create strikingly different mobile versions of sites – simply by creating a new base template.
當然, 他也允許我們使用不同的基本模板創(chuàng)建多個站點的多個版本, django創(chuàng)建者使用這個特性創(chuàng)建網(wǎng)站不同的移動版本.
-
Note that you don’t have to use Django’s template system if you prefer another system. While Django’s template system is particularly well-integrated with Django’s model layer, nothing forces you to use it. For that matter, you don’t have to use Django’s database API, either. You can use another database abstraction layer, you can read XML files, you can read files off disk, or anything you want. Each piece of Django – models, views, templates – is decoupled from the next.
注意, 如果不喜歡可以不用. django的模型, 視圖, 模板都是分離的, 單獨不喜歡某個部分, 可以不用.
-
This is just the surface?
表面
-
This has been only a quick overview of Django’s functionality. Some more useful features:
這些是快速了解django特性的唯一方式:
-
A caching framework that integrates with memcached or other backends.
結(jié)合memcached或者其他的緩存框架
-
A syndication framework that makes creating RSS and Atom feeds as easy as writing a small Python class.
一個使得創(chuàng)建RSS和Atom像寫python類一樣容易的聯(lián)合框架
-
More sexy automatically-generated admin features – this overview barely scratched the surface.
更性感的自動生成管理功能.
-
-
The next obvious steps are for you to download Django, read the tutorial and join the community. Thanks for your interest!
下一步, 請你下載django, 閱讀教程 或者 加入社區(qū).