开始 Django
只需要一个选项,以中文进行以下的释义: Django
我会根据Django的Web应用程序建设教程来记录基本流程。我是在MacOS Sierra 10.12.6上进行操作,所以对其他环境的用户抱歉,此记录可能无法提供参考。
我认为作为Django的特点,可以提到它是一个包含了开发应用所需的全部内容的全栈框架。Django的构成如下所示。

基本架构主要是当收到HTTP请求时,调用与URL路径对应的视图(View),视图从模型(Model)中获取数据并使用模板(Template)对网页进行整合,最终通过HTTP响应返回网页。
在 Model 的 Database 访问中,使用了 ORM(对象关系映射),可以使得与数据库的交互无需编写 SQL。
整治环境
使用pip安装Django。
$ pip install django
我們需要先檢查已安裝的Django版本。
$ python -m django --version
2.0.5
首先,Django允许在一个项目中拥有多个应用程序。您需要先创建一个项目。
$ django-admin startproject mysite
$ cd mysite
mysite/
manage.py
mysite/
__init__.py
settings.py
urls.py
wsgi.py
开启开发服务器,并访问http://127.0.0.1:8000/,如果显示Django页面,则表示环境已经搭建完成。
$ python manage.py runserver
创建最初的应用程序
创建应用程序时,请使用manage.py进行操作。
$ python manage.py startapp polls
polls/
__init__.py
admin.py
apps.py
migrations/
__init__.py
models.py
tests.py
views.py
最初的URL Routing位于urls.py中,View位于views.py中,Model位于models.py中。
首先,我们要编写View。在这里,我们只是简单地返回一个固定的字符串作为Response,而不使用model。
# mysite/polls/views.py
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. You're at the polls index.")
关于URL路由,您需要同时更改应用程序下的url.py文件和项目中的url.py文件。
#mysite/polls/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
]
# mysite/mysite/urls.py
from django.conf.urls import include, url
from django.contrib import admin
from django.urls import path
urlpatterns = [
url(r'^polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]
只需按照先前的步骤启动开发环境服务器,并访问http://127.0.0.1:8000/polls/,即可显示views.py返回的字符串。这样,最简单的初始应用程序就完成了。

创建模型
添加模型,并修改View,以返回从模型获取的数据。
以下是对模型的描述。因为是使用ORM进行描述,所以将在数据库中创建一个名为Question的表和一个名为Choice的表。Question表将包含question_text字段和pub_date字段,Choice表将包含question字段、choice_text字段和vote字段。
# mysite/polls/models.py
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
当使用Django描述模型时,它会帮我们创建数据库表格并生成用于从Python访问数据库的API,但是为了实现这一功能,需要在settings.py中注册应用程序。
# mysite/mysite/settings.py
INSTALLED_APPS = [
'polls.apps.PollsConfig', # <= 追加
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
在Django中,默认情况下使用SQLite作为数据库。
# mysite/mysite/settings.py
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
如果要使用MySQL等数据库,请修改settings.py。
使用以下命令来应用模型更改并创建数据库。
$ python manage.py makemigrations polls
Migrations for 'polls':
polls/migrations/0001_initial.py
- Create model Choice
- Create model Question
- Add field question to choice
$ python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, polls, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying polls.0001_initial... OK
Applying sessions.0001_initial... OK
管理者在系统中输入初始数据。
在Django中,默认情况下会提供一个管理员页面。创建管理员用户,并将默认数据输入到刚刚创建的数据库中。
$ python manage.py createsuperuser
Username : admin
Email address: admin@example.com
Password:
Password (again):
Superuser created successfully.
管理员可以通过以下方式添加选项以更改投票应用程序的模型。
# mysite/polls/admin.py
from django.contrib import admin
from .models import Question
admin.site.register(Question)


在Djongo的shell中验证,数据正确地存入了。
$ python manage.py shell
Python 3.6.4 (default, Mar 1 2018, 18:36:42)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from polls.models import Question, Choice
>>> Question.objects.all()
<QuerySet [<Question: Question object (1)>]>
调整View
修改代码以在视图中从模型中获取数据。由于这次只是想简单地确认与模型的通信,因此我们只需取出先前注册的数据并简单地显示字段数据。
# mysite/polls/views.py
from django.http import HttpResponse
from .models import Question
def index(request):
q = Question.objects.get(id=1)
return HttpResponse(q.question_text)

我已经确认了基本的通信情况。由于我已经理解了Django的基本结构,所以我们将在这里结束。