網站功能html
人們能夠查看投票和選舉python
在管理界面,你能夠添加,修改和刪除投票web
初始化項目目錄結構
在項目文件夾下輸入命令:django
django-admin startproject mysite
項目結構以下:瀏覽器
mysite/ // 這個目錄只是用來存放項目文件的,文件名能夠重命名 manage.py // 一個命令行實用程序,能夠讓你與這個Django項目以不一樣的方式進行交互 mysite/ // 包目錄,(mysite.urls) __init__.py // 空文件,用來指定該目錄是一個包 settings.py // django項目的設置/配置文件 urls.py // 網址入口,關聯到對應的views.py中的一個函數(或者generic類),訪問網址就對應一個函數 wsgi.py // WSGI-compatible web服務器入口,打包文件
運行項目服務器
cd mysite python manage.py runserver
輸出:session
Performing system checks... System check identified no issues (0 silenced). You have 13 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. April 13, 2017 - 05:58:06 Django version 1.11, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C.
新建一個app應用app
python manage.py startapp learn // learn 是一個app的名稱
mysite中會多出一個learn文件夾,目錄以下:ide
learn migrations/ __init__.py admin.py apps.py models.py tests.py views.py
修改mysite/settings.py
修改INSTALLED_APPS函數
INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'learn', )
把learn添加到INSTALL_APPS中,主要是讓Django可以自動找到learn中的模板文件(learn/templates/...)和靜態文件(learn/static/...)
給learn應用定義視圖函數
打開learn/views.py,修改其中源代碼,以下:
#coding:utf-8 from django.http import HttpResponse def index(req): return HttpResponse(u'This is Django Index')
定義視圖函數相關的URL
打開mysite/mysite/urls.py,修改以下:
urlpatterns = patterns('', url(r'^$', 'learn.views.index'), # new # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), )
運行
命令行運行:
python manage.py runserver
輸出:
Performing system checks... System check identified no issues (0 silenced). You have 13 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. April 13, 2017 - 05:58:06 Django version 1.11, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C.
若是是本機訪問頁面,直接訪問:127.0.0.1:8000 就能夠了
因爲我須要再主機上訪問,因此須要運行
python manage.py runserver 0.0.0.0:800
主機訪問頁面
配置主機hosts
在hosts文件
虛擬機ip地址 www.mysite.com
在瀏覽器上訪問 xx.xx.xx.xx:8000
報錯以下:
Invalid HTTP_HOST header: '192.168.150.128:8000'. You may need to add u'192.168.150.128' to ALLOWED_HOSTS. [13/Apr/2017 06:57:55] "GET / HTTP/1.1" 400 61165
修改mysite/mysite/settings.py
修改ALLOWED_HOSTS
ALLOWED_HOSTS = [ '虛擬機ip地址', 'www.mysite.com' ]
在主機瀏覽訪問:xx.xx.xx.xx:8000或者www.mysite.com:8000 頁面輸出 This is Django Index
參考
http://www.ziqiangxuetang.com/django/django-views-urls.html
https://docs.djangoproject.com/en/1.8/ref/settings/#allowed-hosts