glance of django

  • 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ū).

https://docs.djangoproject.com/en/1.11/intro/overview/

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末浮禾,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌甥材,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,627評論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡频丘,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,180評論 3 399
  • 文/潘曉璐 我一進店門泡态,熙熙樓的掌柜王于貴愁眉苦臉地迎上來搂漠,“玉大人,你說我怎么就攤上這事某弦∽创穑” “怎么了?”我有些...
    開封第一講書人閱讀 169,346評論 0 362
  • 文/不壞的土叔 我叫張陵刀崖,是天一觀的道長。 經(jīng)常有香客問我拍摇,道長亮钦,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 60,097評論 1 300
  • 正文 為了忘掉前任充活,我火速辦了婚禮蜂莉,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘混卵。我一直安慰自己映穗,他們只是感情好,可當我...
    茶點故事閱讀 69,100評論 6 398
  • 文/花漫 我一把揭開白布幕随。 她就那樣靜靜地躺著蚁滋,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上辕录,一...
    開封第一講書人閱讀 52,696評論 1 312
  • 那天睦霎,我揣著相機與錄音,去河邊找鬼走诞。 笑死副女,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的蚣旱。 我是一名探鬼主播碑幅,決...
    沈念sama閱讀 41,165評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼塞绿!你這毒婦竟也來了沟涨?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 40,108評論 0 277
  • 序言:老撾萬榮一對情侶失蹤位隶,失蹤者是張志新(化名)和其女友劉穎拷窜,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體涧黄,經(jīng)...
    沈念sama閱讀 46,646評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡篮昧,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,709評論 3 342
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了笋妥。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片懊昨。...
    茶點故事閱讀 40,861評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖春宣,靈堂內(nèi)的尸體忽然破棺而出酵颁,到底是詐尸還是另有隱情,我是刑警寧澤月帝,帶...
    沈念sama閱讀 36,527評論 5 351
  • 正文 年R本政府宣布躏惋,位于F島的核電站,受9級特大地震影響嚷辅,放射性物質(zhì)發(fā)生泄漏簿姨。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 42,196評論 3 336
  • 文/蒙蒙 一簸搞、第九天 我趴在偏房一處隱蔽的房頂上張望扁位。 院中可真熱鬧,春花似錦趁俊、人聲如沸域仇。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,698評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽暇务。三九已至泼掠,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間般卑,已是汗流浹背武鲁。 一陣腳步聲響...
    開封第一講書人閱讀 33,804評論 1 274
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留蝠检,地道東北人沐鼠。 一個月前我還...
    沈念sama閱讀 49,287評論 3 379
  • 正文 我出身青樓,卻偏偏與公主長得像叹谁,于是被迫代替她去往敵國和親饲梭。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 45,860評論 2 361

推薦閱讀更多精彩內(nèi)容