django官方文档1.11编翻:1-1-1概述

django概述

由于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命令查看全部可用的模型,并在数据库中建立不存在的表以及可选地提供更丰富的模式控制的表。后端

享受免费的API

所以,您有一个免费且丰富的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,阅读教程并加入社区。 感谢您的关注!