###### tags: `django` # django入門(五) — 簡單範例(3)-靜態檔 ## IT邦連結(需使用電腦版瀏覽器):[點我前往](https://ithelp.ithome.com.tw/users/20145754/articles) 全部文章: [django入門(一) — 介紹與設定開發環境](https://hackmd.io/@aroncode/SkVeqBO2K) [django入門(二) — 建立資料庫與專案](https://hackmd.io/@aroncode/rkqgL_unY) [django入門(三) — 簡單範例(1)-建立app](https://hackmd.io/@aroncode/H1qirFdhF) [django入門(四) — 簡單範例(2)-範本與範本繼承](https://hackmd.io/@aroncode/rkFuiwKnY) [django入門(五) — 簡單範例(3)-靜態檔](https://hackmd.io/@aroncode/ByL4dFO2Y) [django入門(六) — 資料模型與填充程式](https://hackmd.io/@aroncode/BJot2iRnF) [django入門(七) — Django ORM操作](https://hackmd.io/@aroncode/SJec_hA3Y) ## 簡介: 靜態檔包含css、js以及圖檔。 # 建立靜態檔 按照下方結構建立static資料夾,以及css、js、img的資料夾,並加入main.css和main.js於資料夾下。 ``` main/   static/     main/       css/     main.css       js/      main.js       img/ ``` 將下面css加入main.css ``` html, body { margin: 0; height: 100%; } body { padding: 25px; } .wrapper{ min-height: 100%; /*外層高度100%*/ margin-bottom: 100px; } .title{ border: thin solid gray; border-radius: 10px; padding: 0px; width: 50%; background-color: #DCDAD7; margin-bottom: 25px; } .content{ padding: 10px; border: thin solid gray; border-radius: 10px; width: 60%; } ul#menu { margin-bottom: 30px; text-align: left; } ul#menu li { display: inline-block; font-size: 25px; } .btn { background: linear-gradient(#f7f7f7, #dedede); padding: 0.5em 1em; text-decoration: none; font-family: Arial; display: inline-block; color: black; font-size: 0.8em; border: thin solid gray; } ``` 記得重開伺服器,瀏覽器F5後還是沒有更新頁面的話使用Ctrl+F5。 F5和Ctrl+F5的差別在於,F5是針對瀏覽器緩存做重新整理,而Ctrl+F5是重新向伺服器發出請求。 接著把以下code貼到main.js ``` $(document).ready(function() { var hello = '歡迎~'; alert(hello); }); ``` 回到main/main.html 加入{% load static %}到第二行 以及最下面的script區塊,加入到最下面。 ``` {% extends 'main/base.html' %} {% load static %} {% block heading %}首頁{% endblock %} {% block content %} <h2>{{ hello }}</h2> {% endblock %} {% block script %} <script src="{% static 'main/js/main.js' %}"></script> {% endblock %} ``` Ctrl+F5後如果有跳出歡迎~的字樣代表成功匯入了。 最後示範一下如何載入圖片 下載這個圖片 ![](https://i.imgur.com/HhRFz9o.png =30%x) 將圖片放到static/main/img底下 main/base.html 蓋掉原先的title ``` <div class="title"> <img src="{% static 'main/img/django.png' %}" style="height:8%;width:8%"> <h2 style="display:inline">簡單範例 -- {% block heading %}{% endblock %}</h2> </div> ```