因为Django是在快节奏的新闻编辑室环境中开发的,所以它的设计目的是让常见的Web开发任务变得又快又容易。以下是如何用Django编写数据库驱动的Web应用程序的非正式概述。
本文档的目标是为您提供足够的技术细节来了解Django如何工作,但这并不是教程或参考--但我们两者都有!当您准备好开始一个项目时,您可以 start with the tutorial 或 dive right into more detailed documentation 。
尽管您可以在没有数据库的情况下使用Django,但它带有 object-relational mapper 其中您用Python代码描述数据库布局。
这个 data-model syntax 提供了许多丰富的方法来表示您的模型--到目前为止,它已经解决了多年来的数据库模式问题。这是一个快速例子:
news/models.py
¶from django.db import models
class Reporter(models.Model):
full_name = models.CharField(max_length=70)
def __str__(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):
return self.headline
接下来,运行Django命令行实用程序以自动创建数据库表:
$ python manage.py makemigrations
$ python manage.py migrate
...\> py manage.py makemigrations
...\> py manage.py migrate
这个 makemigrations
命令会查看所有可用的模型,并为不存在的表创建迁移。 migrate
运行迁移并在数据库中创建表,并可选地提供 much richer schema control 。
有了这个,你就有了一个免费的,富有的, Python API 访问您的数据。API是动态创建的,不需要生成代码:
# Import the models we created from our "news" app
>>> from news.models import Article, Reporter
# 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就可以自动创建一个专业的、准备好的生产 administrative interface --一个允许经过验证的用户添加、更改和删除对象的网站。唯一需要的步骤是在管理站点中注册您的模型:
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)
news/admin.py
¶from django.contrib import admin
from . import models
admin.site.register(models.Article)
这里的理念是,您的网站由员工或客户编辑,或者可能只是您编辑-并且您不想只为了管理内容而创建后台界面。
创建Django应用程序的一个典型工作流程是创建模型并尽快启动和运行管理站点,以便您的员工(或客户)可以开始填充数据。然后,制定向公众展示数据的方式。
一个干净、优雅的URL方案是高质量Web应用程序的重要细节。Django鼓励漂亮的URL设计,并且不会在URL中放任何东西,比如 .php
或 .asp
。
要为应用程序设计URL,请创建一个名为 URLconf .您的应用程序的内容表,它包含URL模式和Python回调函数之间的映射。URLConfs还可以将URL与Python代码脱钩。
以下是URLinf的外观 Reporter
/Article
上面的例子:
news/urls.py
¶from django.urls import path
from . import views
urlpatterns = [
path("articles/<int:year>/", views.year_archive),
path("articles/<int:year>/<int:month>/", views.month_archive),
path("articles/<int:year>/<int:month>/<int:pk>/", views.article_detail),
]
上面的代码将URL路径映射到Python回调函数(“视图”)。路径字符串使用参数标签从URL中“捕获”值。当用户请求页面时,Django会按顺序运行每个路径,并在第一个与请求的URL匹配的路径处停止。(If Django称之为特殊情况404视图,它们都不匹配。)这速度非常快,因为路径在加载时被编译成正规表达式。
一旦其中一个URL模式匹配,Django就会调用给定的视图,这是一个Python函数。每个视图都会传递一个请求对象(其中包含请求元数据)以及模式中捕获的值。
例如,如果用户请求URL“/articles/2005/05/39323/”,Django将调用该函数 news.views.article_detail(request, year=2005, month=5, pk=39323)
。
每个视图负责执行以下两件事之一:返回 HttpResponse
包含请求页面内容的对象,或引发异常,例如 Http404
.剩下的就看你了。
通常,视图根据参数检索数据,加载模板并使用检索到的数据渲染模板。这是一个示例视图 year_archive
从上面看:
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的 template system ,它具有几个强大的功能,但努力保持足够简单,供非程序员使用。
上面的代码加载 news/year_archive.html
模板。
Django有一个模板搜索路径,可以让您最大限度地减少模板之间的冗余。在Django设置中,您指定要检查模板的目录列表 DIRS
.如果第一个目录中不存在模板,则会检查第二个目录,以此类推。
我们假设 news/year_archive.html
找到了模板。这是它可能的样子:
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 }}
意思是“输出文章标题属性的值。“但点不仅仅用于属性查找。它们还可以进行字典键查找、索引查找和函数调用。
注意事项 {{ article.pub_date|date:"F j, Y" }}
使用Unix风格的“管道”(“|“性格)。这称为模板过滤器,是过滤变量值的一种方法。在这种情况下,日期过滤器以给定格式格式化Python日期时间对象(如PHP的日期函数中所示)。
您可以将任意多的过滤器链接在一起。你可以写 custom template filters .你可以写 custom template tags ,它们在幕后运行自定义Python代码。
最后,Django使用了“模板继承”的概念。是这么 {% extends "base.html" %}
可以这它的意思是“首先加载名为‘base’的模板,该模板定义了一堆块,并用以下块填充这些块。“简而言之,这可以极大地减少模板中的冗余:每个模板必须仅定义该模板的独特性。
以下是“base.html”模板的内容,包括使用 static files ,可能看起来像:
templates/base.html
¶{% load static %}
<html lang="en">
<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。您可以使用另一个数据库抽象层,可以读取ML文件,可以从磁盘上读取文件,或任何您想要的内容。Django的每一部分--模型、视图、模板--都与下一部分脱钩。
这只是Django功能的快速概述。一些更有用的功能:
A caching framework 它与memcached或其他后台集成。
A syndication framework 它允许您通过编写一个小型Python类来创建RSS和Atom提要。
更有吸引力的自动生成管理功能--这个概述几乎没有触及表面。
接下来的步骤是您要 download Django ,阅读 the tutorial 并加入 the community .感谢您的兴趣!
5月 28, 2025