Django in Ubuntu part0
installed Django Version:1.11.17
use python 2.7
1. 安装
root@iZwz969jm0y04abuhgx4byZ:~# apt-get install python-setuptools
root@iZwz969jm0y04abuhgx4byZ:~# python -m pip install "django<2"
root@iZwz969jm0y04abuhgx4byZ:~# python
Python 2.7.12 (default, Nov 12 2018, 14:36:49)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> django.VERSION
(1, 11, 17, u'final', 0)
>>>
如果python版本为3.5以上,可以使用 easy_install django
安装。
2. 创建新项目
使用pip 安装的话,用
root@iZwz969jm0y04abuhgx4byZ:~# django-admin.py
Note that only Django core commands are listed as settings are not properly configured (error: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.).
root@iZwz969jm0y04abuhgx4byZ:~# django-admin startproject HelloWorld
root@iZwz969jm0y04abuhgx4byZ:~# cd HelloWorld/
root@iZwz969jm0y04abuhgx4byZ:~/HelloWorld# tree
.
├── HelloWorld
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── manage.py
1 directory, 5 files
Error:Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings
Solve: django-admin 不要py
Error: DisallowedHost at / Invalid HTTP_HOST header
Solve: 将项目名称下的 settings.py
中的 ALLOWED_HOSTS = []
改成 ALLOWED_HOSTS = ['*']
3. 视图和URL配置
3.1 视图
在先前创建的 HelloWorld 目录下的 HelloWorld 目录新建一个 view.py 文件,并输入代码:
from django.http import HttpResponse
def hello(request):
return HttpResponse("Hello world ! ")
3.2 URL配置
接着,绑定 URL 与视图函数。打开 urls.py 文件,删除原来代码,将以下代码复制粘贴到 urls.py 文件中:
from django.conf.urls import url
from . import view
urlpatterns = [
url(r'^$', view.hello),
]
#3.3 编译
不需要,服务器会自动在更改后编译
随后编译 view.py
和 urls.py
文件
root@iZwz969jm0y04abuhgx4byZ:~/HelloWorld/HelloWorld# python -m py_compile urls.py
3.4 打开服务器
注:如果是 Django >= 2.0 的版本,urls.py
的 django.conf.urls
已经被 django.urls
取代。
django.urls 的用法参考如下:
from django.urls import path
from . import view
urlpatterns = [
path('', view.hello),
path('world/', view.world)
]
其中最大的几个改变如下:
import url 变成了 import path
如果是路径,则须在路径后加个/
旧版 django 的用法:
from django.conf.urls import url
from . import view
urlpatterns = [
url(r'^hello$', view.hello),
]
新版的参考写法:
from django.urls import path
from . import view
urlpatterns = [
path('hello/', view.hello),
]