-
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是在一个快节奏的新闻环境下诞生的, 所以它的目的是使普通的web开发任务快速且容易. 以下关于如何编写一个数据库驱动的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.
本文的目的是给予足够多的细节让你明白django是如何工作的. 但这并不意味着这就是教程或者参考—— 我们已经有教程和参考了. 当你准备开始一个项目时, 可以直接从教程开始, 也可以进入更详细的文档中去
-
Design your model¶
设计你的模型
-
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时不会使用数据库, 但他所具备的对象关系映射功能, 能够让我们用python代码来创建或者使用数据库.
-
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:
数据模型语法提供了丰富的方法来表示你的模型. 到现在为止, 它已经解决了多年的数据库模式问题. 下面是一个快速的例子:
-
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:
接着, 通过命令到数据库中创建表.
$ 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.
-
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:
到目前为止,已经有免费且丰富的接口来访问数据库.这些接口时的创建, 不需要额外的代码.
# 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.
# 目前数据中还没有内容
>>> 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.
# 保存对象到数据库. 必须call save() .
>>> r.save()
# Now it has an ID.
# 现在就有了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.
# 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.
# 创建的数据到数据库中去了
>>> 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()
-
A dynamic admin interface: it’s not just scaffolding – it’s the whole house¶
一个动态的管理界面: 他只是架子, 而是整个房子.
-
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可以自动创建一个专业的, 生产准备的管理界面, 可以对用户进行添加, 更改, 删除.
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.
这里的理念是, 你的站点由一个人编写, 同时你不想为了管理内容添加后端接口.
-
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中的典型工作流程是, 为了创建model 去创建apps , 然后尽快把相关表注册到管理界面, 然后运行, 最后是开发可以面向公众的页面或者接口.
-
Design your URLs¶
设计你的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.
干净, 优雅的url方案是高质量web应用程序的重要环节, django鼓励设计漂亮的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设计urls, 你可以创建一个叫做URLconf 的模块, 它需要配置你app中url和url 函数的对应关系, 作为映射.
-
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回调函数, 也就是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.
一旦匹配上了给定的视图, 每个视图函数传入的参数为请求对象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, 同时传入的参数为(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:
一般来说, 视图根据参数检索数据, 使用检索后的数据加载模板. 比如:
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的模板系统,功能强大, 对非程序员来说也足够简单.
-
Design your templates¶
设计你的模板
-
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:
模板的内容:
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属性. 当然, 还可以用于字典键, 索引, 和函数调用.
-
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" %}处. 它首先加载这个模板, 然后用下面的内容填充加载的模板中的块. 能够减少模板的冗余.
-
Here’s what the “base.html” template, including the use of static files, might look like:
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>
-
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.
简单来说, 它定义了网站的外观和感觉(和网站logo), 多种技术使得网站重新设计变得很简单.
-
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.
当然, 他也允许我们使用不同的基本模板创建多个站点的多个版本, django创建者使用这个特性创建网站不同的移动版本.
-
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.
结合memcached或者其他的缓存框架
-
A syndication framework that makes creating RSS and Atom feeds as easy as writing a small Python class.
一个使得创建RSS和Atom像写python类一样容易的联合框架
-
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, 阅读教程 或者 加入社区.
网友评论