准备
$ conda create --name django python=3 /* 创建anaconda虚拟环境,名字django,python版本3 */
$ source activate django /* 激活虚拟环境 */
# conda install django /* 安装django */
测试
$ django-admin /* 查看子命令清单,回显如下 */
Type 'django-admin help <subcommand>' for help on a specific subcommand.
Available subcommands:
[django]
…………
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.).
红色部分翻译如下:
注意,只有Django核心命令被列出,因为settings没有正确配置(错误:请求设置INSTALLED_APPS,但没有成功。在访问设置之前,你必须定义环境变量DJANGO_SETTINGS_MODULE或调用settings.configure()。)
原因:setting是指项目的setting.py文件,这里还没有创建项目,自然不存在setting.py文件。
创建项目
$ django-admin startproject HelloWorld /* 创建项目 */
$ cd HelloWorld /* 进入项目路径 */
$ tree /* 查看树结构 */
.
├── HelloWorld
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── manage.py
启动项目
$ python3 manage.py runserver 0.0.0.0:8000 /* 启动项目 */
报错:
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.
解决错误:
$ python manage.py migrate /* 应用迁移 */
$ python3 manage.py runserver 0.0.0.0:8000 /* 启动项目 */
访问项目
查询django所在虚拟机的ip,通过宿主机的浏览器访问之。
报错:Invalid HTTP_HOST header: <ip> You may need to add <ip> to ALLOWED_HOST.
解决错误:打开项目的settings.py文件,找到ALLOWED_HOST,修改为:
ALLOWED_HOSTS = ['<ip>'] /* <ip>是django所在虚拟机的ip */
重新启动项目
$ python3 manage.py runserver 0.0.0.0:8000 /* 启动项目 */
再次通过浏览器访问,成功。