python学习笔记08:安装django

linux环境安装django:

sudo pip install django

windows环境安装django:

pip install django

验证django是否安装:

python -m django --version

切换目录到E:\SourceCode,创建新项目,项目名称为:mysite:

django-admin startproject mysite

切换到mysite目录,运行mysite项目:

python manage.py runserver

在mysite项目中,创建polls应用:

python manage.py startapp polls

开始编写第一个页面,打开polls/views.py:

from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
return HttpResponse("Hello, world. You're at the polls index.")

此时django还不能访问到polls应用的view,因为缺少路由信息,下面要配置路由信息:
新增并打开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'^polls/', include('polls.urls')),
url(r'^admin/', admin.site.urls),
]

添加路由的方法,有几种,根据不同的情况来使用。

第一种(Function views):

1.首先导入view的模块,from . import views

2.在urlpatterns中插入新的路由,url(r'^$', views.index, name='index')

第二种(Class-based views):

1.首先导入view的模块,from other_app.views import Home

2.在urlpatterns中插入新的路由,url(r'^$', Home.as_view(), name='home')

第三种(Including another URLconf):

1.首先导入include()函数,from django.conf.urls import include, url

2.在urlpatterns中插入新的路由,url(r'^polls/', include('polls.urls'))

先初始化mysite项目的数据库:

python manage.py migrate

配置完成后,运行mysite项目:

python manage.py runserver

上一篇:python排序 sorted()与list.sort() (转)


下一篇:Linux下安装Django