古之善為士者,微妙玄通,深不可識
——老子《道德經(jīng)》
本節(jié)內(nèi)容
- 給頁面添加樣式修飾
1. 頁面樣式處理
通常情況下,網(wǎng)頁開發(fā)時,頁面中的樣式是通過外部css樣式進(jìn)行處理的,外部的css文件加載在Django中,需要進(jìn)行簡單的處理
首先取保我們的mysite/mysite/settings.py配置文件中,包含了STATIC_URL='/static/'的配置(默認(rèn)是已經(jīng)配置的)
我們在應(yīng)用模塊文件夾下,創(chuàng)建一個目錄static/專門用于存放css樣式文件,創(chuàng)建一個目錄images/專門保存頁面中用到的圖片,創(chuàng)建一個lib/專門用于保存第三方的文件(如jquery、bootstrap等等)
創(chuàng)建mysite/polls/static/style.css樣式文件,用于修飾我們的首頁index.html樣式,編輯內(nèi)容如下
*{margin:0;padding:0;}
h1{font-size:18px;color:#069;font-weight:bolder;}
ul{list-style:none;font-size:16px;}
ul > li{height:20px;line-height:20px;font-family: "微軟雅黑"}
因?yàn)槲覀兊捻?xiàng)目是用在網(wǎng)絡(luò)服務(wù)器上的,所以在mysite/polls/templates/index.html文件中引入樣式,首先要通過{%load static%}獲取static/文件夾的絕對路徑,然后在頁面中,使用{% static '路徑'%}的形式來使用;
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
{% load static %}
<link rel="stylesheet" href="{% static 'polls/style.css' %}">
<title>投票模塊首頁</title>
<link rel="stylesheet" href="">
</head>
<body>
<h1>投票模塊首頁</h1>

{%if question_list%}
<ul>
{%for question in question_list%}
<li><a href="{%url 'polls:detail' question.id%}">{{question.question_text}}</a></li>
{%endfor%}
</ul>
{%else%}
<p>Congratulations,目前沒有什么問題</p>
{%endif%}
</body>
</html>
完成上述代碼之后,我們打開網(wǎng)頁訪問應(yīng)用的首頁,就可以看到我們的樣式和圖片都加載OK了
網(wǎng)頁中使用樣式和圖片
2. 使用第三方模塊Bootstrap
進(jìn)入http://www.bootcss.com下載bootstrap框架文件,這里我使用的是bootstrap3.4的版本。下載好之后,將解壓得到的bootstrap文件中的css/、js/、font/三個文件拷貝到我們項(xiàng)目的mysite/polls/static/lib/文件夾下
bootstrap中文官網(wǎng)
項(xiàng)目目錄結(jié)構(gòu)
項(xiàng)目目錄結(jié)構(gòu)
接下來,我們編輯mysite/polls/templates/index.html頁面,引入bootstrap并添加它的樣式處理如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
{% load static %}
<link rel="stylesheet" href="{% static 'polls/lib/bootstrap3.4/css/bootstrap.min.css' %}">
<title>投票模塊首頁</title>
<link rel="stylesheet" href="">
</head>
<body>
<div class="container">
<div class="row">
<div class="page-header">
<h1>用戶問題列表 <small>解決方案提供平臺</small></h1>
</div>
</div>
<div class="row">
{%if question_list%}
<table class="table table-hover table-striped">
<tr>
<th>問題編號</th>
<th>問題描述</th>
<th>操作</th>
</tr>
{%for question in question_list%}
<tr>
<td>{{forloop.counter}}</td>
<td>{{question.question_text}}</td>
<td><a href="{% url 'polls:vote' question.id%}">查看詳細(xì)</a></td>
</tr>
{%endfor%}
</table>
{%else%}
<p>Congratulations,目前沒有什么問題</p>
{%endif%}
</div>
</div>
</body>
</html>
重新啟動項(xiàng)目,我們打開瀏覽器訪問項(xiàng)目首頁,可以看到一個非常漂亮的首頁呈現(xiàn)在了眼前

本節(jié)內(nèi)容對于靜態(tài)文件(如樣式表文件css、腳本文件js、圖片文件image)的處理就說到這里。大家如果有什么問題的話可以留言的哦!



