本章我们将介绍django 管理工具及如何使用 django 来创建项目,第一个项目我们以 helloworld 来命令项目。
安装 django 之后,您现在应该已经有了可用的管理工具 django-admin.py。我们可以使用 django-admin.py 来创建一个项目:
我们可以来看下django-admin.py的命令介绍:
[root@solar ~]# django-admin.py usage: django-admin.py subcommand [options] [args] options: -v verbosity, --verbosity=verbosity verbosity level; 0=minimal output, 1=normal output, 2=verbose output, 3=very verbose output --settings=settings the python path to a settings module, e.g. "myproject.settings.main". if this isn't provided, the django_settings_module environment variable will be used. --pythonpath=pythonpath a directory to add to the python path, e.g. "/home/djangoprojects/myproject". --traceback raise on exception --version show program's version number and exit -h, --help show this help message and exit type 'django-admin.py help <subcommand>' for help on a specific subcommand. available subcommands: [django] check cleanup compilemessages createcachetable ……省略部分……
使用 django-admin.py 来创建 helloworld 项目:
django-admin.py startproject helloworld
创建完成后我们可以查看下项目的目录结构:
[root@solar ~]# cd helloworld/ [root@solar helloworld]# tree . |-- helloworld | |-- __init__.py | |-- settings.py | |-- urls.py | `-- wsgi.py `-- manage.py
目录说明:
接下来我们进入 helloworld 目录输入以下命令,启动服务器:
python manage.py runserver 0.0.0.0:8000
0.0.0.0让其它电脑可连接到开发服务器,8000为端口号。如果不说明,那么端口号默认为8000。
在浏览器输入你服务器的ip及端口号,如果正常启动,输出结果如下:
在先前创建的 helloworld 目录下的 helloworld 目录新建一个 view.py 文件,并输入代码:
from django.http import httpresponse def hello(request): return httpresponse("hello world ! ")
接着,绑定 url 与视图函数。打开 urls.py 文件,删除原来代码,将以下代码复制粘贴到 urls.py 文件中(django 1.6 如果报错,就使用“from django.conf.urls.defaults import”):
from django.conf.urls import url from . import view urlpatterns = [ url(r'^$', view.hello), ]
整个目录结构如下:
$ tree . |-- helloworld | |-- __init__.py | |-- __init__.pyc | |-- settings.py | |-- settings.pyc | |-- urls.py # url 配置 | |-- urls.pyc | |-- view.py # 添加的视图文件 | |-- view.pyc # 编译后的视图文件 | |-- wsgi.py | `-- wsgi.pyc `-- manage.py
完成后,启动 django 开发服务器,并在浏览器访问打开浏览器并访问:
注意:项目中如果代码有改动,服务器会自动监测代码的改动并自动重新载入,所以如果你已经启动了服务器则不需手动重启。