用Django在30分钟内开始制作Web应用(直到完成“Hello World”)

由于有机会接触Django,我按照2.1版本的官方文档教程尝试了一下,并记录了工作日志。

    • クイックインストールガイド | Django ドキュメント | Django

 

    はじめての Django アプリ作成、その 1 | Django ドキュメント | Django

标题有点夸张了。在安装pip和限制访问的部分花了大约45分钟的时间。

准备Ubuntu服务器。

我使用Vagrant的ubuntu/bionic64进行了搭建。

vagrant@django-serv:~$ cat /etc/lsb-release 
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=18.04
DISTRIB_CODENAME=bionic
DISTRIB_DESCRIPTION="Ubuntu 18.04.2 LTS"
vagrant@django-serv:~$ 

以下のように中国語で自然な形で言い換えます(オプションは一つだけ):
Python环境是

vagrant@django-serv:~$ python3 --version
Python 3.6.7
vagrant@django-serv:~$ python3
Python 3.6.7 (default, Oct 22 2018, 11:32:17) 
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'django'
>>> 
vagrant@django-serv:~$ 

Django尚未安装。

让我们立即开始吧。

假设以下,虚拟机的IP地址为192.168.244.201。

Django 安装

Django 文件 | 快速安装指南 | Django

请参考这里的Django代码安装步骤。

vagrant@django-serv:~$ pip install Django==2.1

Command 'pip' not found, but can be installed with:

apt install python-pip
Please ask your administrator.

vagrant@django-serv:~$ 

哦…

安装pip

vagrant@django-serv:~$ sudo apt install python-pip
Reading package lists... Done
Building dependency tree       
Reading state information... Done
:
:

大量的软件包已安装,但这是2.7版本的。正确答案是python3-pip。

vagrant@django-serv:~$ sudo apt install python3-pip
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following additional packages will be installed:
  dh-python libpython3-dev libpython3.6-dev python3-crypto python3-dev
  python3-distutils python3-keyring python3-keyrings.alt python3-lib2to3
  python3-secretstorage python3-setuptools python3-wheel python3-xdg
  python3.6-dev
Suggested packages:
  python-crypto-doc gnome-keyring libkf5wallet-bin gir1.2-gnomekeyring-1.0
  python-secretstorage-doc python-setuptools-doc
The following NEW packages will be installed:
  dh-python libpython3-dev libpython3.6-dev python3-crypto python3-dev
  python3-distutils python3-keyring python3-keyrings.alt python3-lib2to3
  python3-pip python3-secretstorage python3-setuptools python3-wheel
  python3-xdg python3.6-dev
vagrant@django-serv:~$ ll /usr/bin/pip*
-rwxr-xr-x 1 root root 292 May 16  2018 /usr/bin/pip*
-rwxr-xr-x 1 root root 292 May 16  2018 /usr/bin/pip2*
-rwxr-xr-x 1 root root 293 May 16  2018 /usr/bin/pip3*

嗯…

安装Django

vagrant@django-serv:~$ pip3 install Django==2.1
Collecting Django==2.1
  Downloading https://files.pythonhosted.org/packages/51/1a/e0ac7886c7123a03814178d7517dc822af0fe51a72e1a6bff26153103322/Django-2.1-py3-none-any.whl (7.3MB)
    100% |████████████████████████████████| 512kB 1.8MB/s 
Installing collected packages: pytz, Django
Successfully installed Django-2.1 pytz-2019.1
vagrant@django-serv:~$ python3
Python 3.6.7 (default, Oct 22 2018, 11:32:17) 
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> print(django.get_version())
2.1
>>> 
vagrant@django-serv:~$ python -m django --version
/usr/bin/python: No module named django
vagrant@django-serv:~$ python3 -m django --version
2.1
vagrant@django-serv:~$ python --version
Python 2.7.15rc1
vagrant@django-serv:~$ 

唉,只因为安装了Python 2,所以弄得麻烦了。
等会再重新做吧。

创建应用程序

创建项目

vagrant@django-serv:~src$ which django-admin
vagrant@django-serv:~src$ 

嗯?

vagrant@django-serv:~src$ django-admin startproject mysite

Command 'django-admin' not found, but can be installed with:

apt install python-django-common
Please ask your administrator.

vagrant@django-serv:~src$ 

哎呀?

我去找的时候,竟然在这里找到了。

vagrant@django-serv:~src$ ls ~/.local/bin/
__pycache__  django-admin  django-admin.py
vagrant@django-serv:~src$ export PATH=$PATH:~/.local/bin
vagrant@django-serv:~src$ which django-admin
/home/vagrant/.local/bin/django-admin
vagrant@django-serv:~src$ 
vagrant@django-serv:~src$ django-admin startproject mysite
vagrant@django-serv:~src$ ls
mysite
vagrant@django-serv:~src$ 
vagrant@django-serv:~/src$ tree
.
└── mysite
    ├── manage.py
    └── mysite
        ├── __init__.py
        ├── settings.py
        ├── urls.py
        └── wsgi.py

2 directories, 5 files
vagrant@django-serv:~/src$ 

启动开发用服务器

我进入项目并执行 python3 manage.py runserver。

vagrant@django-serv:~/src$ cd mysite/
vagrant@django-serv:~/src/mysite$ python3 manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).

You have 15 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.

May 21, 2019 - 11:58:13
Django version 2.1, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

只有从本地主机上才能访问的服务器将在local主机上启动。由于是在虚拟机上运行,只能从本地主机使用curl访问。

再启动一个Shell,运行curl命令,将显示以下访问日志。

May 21, 2019 - 11:58:13
Django version 2.1, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
[21/May/2019 12:00:38] "GET / HTTP/1.1" 200 16348

由于这样理解起来比较困难,建议您先按下Ctrl-c停止,然后重新启动并监听0.0.0.0。

vagrant@django-serv:~/src/mysite$ python3 manage.py runserver 0:8000
Performing system checks...

System check identified no issues (0 silenced).

You have 15 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.

May 21, 2019 - 12:03:09
Django version 2.1, using settings 'mysite.settings'
Starting development server at http://0:8000/
Quit the server with CONTROL-C.

从浏览器访问。

2019-05-21_21h04_29.png

哎呀呀…
默认限制了访问吗。

Django version 2.1, using settings 'mysite.settings'
Starting development server at http://0:8000/
Quit the server with CONTROL-C.
Invalid HTTP_HOST header: '192.168.244.201:8000'. You may need to add '192.168.244.201' to ALLOWED_HOSTS.
Bad Request: /
[21/May/2019 12:03:26] "GET / HTTP/1.1" 400 59658
Invalid HTTP_HOST header: '192.168.244.201:8000'. You may need to add '192.168.244.201' to ALLOWED_HOSTS.
Bad Request: /favicon.ico
[21/May/2019 12:03:27] "GET /favicon.ico HTTP/1.1" 400 59574
--- mysite/settings.py.org      2019-05-21 11:53:40.067134637 +0000
+++ mysite/settings.py  2019-05-21 12:12:18.185914636 +0000
@@ -27,3 +27,3 @@

-ALLOWED_HOSTS = []
+ALLOWED_HOSTS = ["192.168.244.201"]

如果您不需要考虑本地虚拟机等外部访问控制,可以将ALLOWED_HOSTS的内容设置为[“*”]。

在Django 1.5及以上的版本中,需要进行ALLOWED_HOSTS的配置-ymyzk的博客

重新集中精神,再次执行。

image.png
vagrant@django-serv:~/src/mysite$ python3 manage.py runserver 0:8000
Performing system checks...

System check identified no issues (0 silenced).

You have 15 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.

May 21, 2019 - 12:12:48
Django version 2.1, using settings 'mysite.settings'
Starting development server at http://0:8000/
Quit the server with CONTROL-C.
[21/May/2019 12:12:49] "GET / HTTP/1.1" 200 16348
[21/May/2019 12:12:49] "GET /static/admin/css/fonts.css HTTP/1.1" 200 423
[21/May/2019 12:12:49] "GET /static/admin/fonts/Roboto-Bold-webfont.woff HTTP/1.1" 200 82564
[21/May/2019 12:12:49] "GET /static/admin/fonts/Roboto-Regular-webfont.woff HTTP/1.1" 200 80304
[21/May/2019 12:12:49] "GET /static/admin/fonts/Roboto-Light-webfont.woff HTTP/1.1" 200 81348

创建应用程序

按照教程的指示,创建一个名为”投票应用”的应用程序。
执行的命令是python3 manage.py startapp polls。

我在想,也许不在mysite目录下创建,按照教程在manage.py同一层级创建。

vagrant@django-serv:~/src/mysite$ ls
db.sqlite3  manage.py  mysite
vagrant@django-serv:~/src/mysite$ ls mysite/
__init__.py  __pycache__  settings.py  settings.py.org  urls.py  wsgi.py
vagrant@django-serv:~/src/mysite$ python3 manage.py startapp polls
vagrant@django-serv:~/src/mysite$ ls
db.sqlite3  manage.py  mysite  polls
vagrant@django-serv:~/src/mysite$ tree
.
├── db.sqlite3
├── manage.py
├── mysite
│   ├── __init__.py
│   ├── __pycache__
│   │   ├── __init__.cpython-36.pyc
│   │   ├── settings.cpython-36.pyc
│   │   ├── urls.cpython-36.pyc
│   │   └── wsgi.cpython-36.pyc
│   ├── settings.py
│   ├── settings.py.org
│   ├── urls.py
│   └── wsgi.py
└── polls
    ├── __init__.py
    ├── admin.py
    ├── apps.py
    ├── migrations
    │   └── __init__.py
    ├── models.py
    ├── tests.py
    └── views.py

4 directories, 18 files
vagrant@django-serv:~/src/mysite$ 

创建View

打开polls/views.py文件。由于文件为空,因此按照教程中的代码进行实现。
请注意模板和引用的初始状态已经有所变化。

from django.http import HttpResponse

# Create your views here.
def index(request):
    return HttpResponse("カレーは粉でできてるのでカロリーゼロ. You're at the polls index.")

创建URLconf

突然出现了URLconf这个词,它是用来设置调用已创建的视图所需的URL的工具,类似于这样的感觉吧?
创建polls/urls.py文件。

from django.urls import path

from . import views

urlpatterns = [
    path('', views.index, name='index'),
]

路径()的参数在教程第一页的末尾有提及,请参考。

接下来,在mysite/urls.py中导入上述polls/urls.py的内容。

--- mysite/urls.py.org  2019-05-21 11:53:40.067134637 +0000
+++ mysite/urls.py      2019-05-21 12:26:52.223474670 +0000
@@ -16,5 +16,6 @@
 from django.contrib import admin
-from django.urls import path
+from django.urls import include, path

 urlpatterns = [
+    path('polls/', include('polls.urls')),
     path('admin/', admin.site.urls),

通过运行命令 “python3 manage.py runserver 0:8000” 重新进行测试,并在浏览器中访问 /polls/ 页面。

image.png

动起来了(・∀・)

广告
将在 10 秒后关闭
bannerAds