前一段時間,用Django搭建一個報表分析的網站;借此正好整理一下筆記。
1. 安裝
python有包管理工具pip,直接cd Python27/Scripts
,輸入
pip install django
# install by version
pip install --upgrade Django==<version>
安裝完成后,python -c "import django; print(django.get_version())"
,若能打印出Django的版本信息,即說明安裝成功。一般地,Django安裝在Python27/Lib/site-package/django
目錄。
2. Django介紹
項目
Django的架構是MTV(Model-Template-View)。輸入命令
python <path>/Python27/Lib/site-packages/django/bin/django-admin.py startproject mysite
創建mysite的Django項目,項目的文件目錄如下:
mysite/
manage.py
mysite/
__init__.py
settings.py
urls.py
wsgi.py
- 最外層的mysite目錄包含了整個項目,與Django沒有半毛錢的直接關系,可改名。
- manage.py提供對項目的命令行(command-line)操作,比如:python manage.py runserver開啟服務,默認端口號為8000(若開啟端口號為8888,則python manage.py runserver 8888)。
- 內層的mysite文件夾是python package,與項目名相對應。
__init__.py
為空文件,表示mysite是一個package。- settings.py為項目的配置文件。
- wsgi.py為WSGI-compatible web servers。
app
輸入python manage.py startapp polls
,為項目創建了Polls app,文件目錄結構如下:
polls/
__init__.py
admin.py
apps.py
migrations/
__init__.py
models.py
tests.py
views.py
app定義網站內容view與model層,view.py定義網站數據的獲取,而網頁格式規范是在HTML Template中所定義的。比如,在source.html中定義網頁:
{% extends "base.html" %}
{% block main %}
<table class="info" cellspacing="0" width="100%">
<thead>...</thead>
<tbody>
<tr>
<td>{{firstWeekDay}}</td>
</tr>
</tbody>
</table>
通過view層向html注入數據(通過context給HTML中定義變量賦值):
# views.py
from django.shortcuts import render_to_response
def source(request):
context = {}
context.update(firstWeekDay=fourWeek[0])
return render_to_response('source.html', context)
上面通過命令建項目的方式可能過於繁瑣,PyCharm是IDE中不錯一個選擇,可用來快速構建Django項目。
3. 實戰
循環注入
Django支持注入數據的格式為迭代集合如tuple、list等,用for循環依次取出:
<!-- list -->
<tbody>
<tr>
<td>{{firstWeekDay}}</td>
{% for pv in firstWeekPv %}
<td>{{pv}}</td>
{% endfor %}
</tr>
</tbody>
<!-- list of tuple -->
<tbody>
{% for ad in adParent %}
<tr>
<td>{{ad.0}}</td>
<td>{{ad.1}}</td>
<td>{{ad.2}}</td>
<td>{{ad.3}}</td>
</tr>
{% endfor %}
</tbdoy>
靜態導入
Django同時支持導入靜態css、js文件等,建議使用絕對路徑作為root;這些配置信息須在settings.py中添加:
STATIC_ROOT = '<path>/to/static'
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
('css', os.path.join(STATIC_ROOT, 'css').replace('\\', '/')),
('js', os.path.join(STATIC_ROOT, 'js').replace('\\', '/')),
('images', os.path.join(STATIC_ROOT, 'images').replace('\\', '/'))
)
如此,可以在HTML中自由地導入相對路徑了:
<link rel="stylesheet" type="text/css" href="/static/css/style.css"/>
<script type="text/javascript" src="/static/js/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="/static/js/jquery.dataTables.min.js"></script>