Django 环境搭建 及 第一个项目
安装python
安装pip
用get-pip.py来安装pip:https://pip.pypa.io/en/latest/installing.html
Linux, Mac OSX, Windows下均可以使用该方法
升级pip
pip install --upgrade pip
安装Django
pip install Django
检查Django是否安装成功
如果成功,会输出Django版本号
python -c "import django; print(django.get_version())"
创建项目
在命令行cd到一个想在该位置创建项目的位置,执行如下代码(mysite为项目名称)
django-admin startproject mysite
需要注意两点:
You’ll need to avoid naming projects after built-in Python or Django components. In particular,
this means you should avoid using names like django (which will conflict with Django itself) or
test (which conflicts with a built-in Python package).Where should this code live?
If your background is in plain old PHP (with no use of modern frameworks),
you’re probably used to putting code under the Web server’s document root (in a place such as /var/www).
With Django, you don’t do that.
It’s not a good idea to put any of this Python code within your Web server’s document root,
because it risks the possibility that people may be able to view your code over the Web.
That’s not good for security.
Put your code in some directory outside of the document root, such as /home/mycode.
运行项目(该内置服务器仅限于开发时使用)
python manage.py runserver
or
python manage.py runserver 8080
or
python manage.py runserver 0.0.0.0:8000
在mysite项目下创建一个名字为polls的应用
python manage.py startapp polls
分别编辑如下文件:
polls/views.py
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. You're at the polls index.")
创建polls/urls.py,并添加如下代码
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
]
mysite/urls.py
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^polls/', include('polls.urls')),
]
创建项目、应用以及其他详细说明 参见Django官方新手文档