[Django] using bootstrap template by staticfile

George
George’s Note & Idea
5 min readFeb 21, 2019

--

首先你需要新增django project and app

> django-admin startproject [django_project_name]
> cd [django_project_name]
> python manage.py startapp [django_app]
> ...

(略過專案建立步驟…)

  1. 設定settings.py,並增加兩個部分。

settings.py的template設定

TEMPLATES = [
{
'DIRS': [os.path.join(BASE_DIR, 'templates')],
},
]

settings.py的static設定

STATIC_URL = '/static/'STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]

2. 在django專案下增加static檔案 (ex: django_project/static/)

> mkdir static

3. 搜尋你所喜愛的bootstrap template範例,並下載。

然後,將檔案放到[django_project_name]/static裡面

由於使用django template,我們的html都會集中在/templates裡面,故把static裡面的html移到templates裡面。

然後,針對index.html開始進行修改,優先把首頁先建立起來。

4. 增加views.py

# views.py
def index(request):
template = 'index.html'
context = {}
return render(request, template, context)

5. 修改urls.py

# urls.py
from django.contrib import admin
from django.urls import path
from app import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', views.index, name='index'),
]

6. 修改index.html,需要在檔案前面增加{% load staticfile %} 或 {% load static %}

{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
</body>
</html>

啟動django之後,看到的畫面會不太好看。那是因為bootstrap的js, css等資料路徑都是錯誤的,所以不會顯示。

修改js/css路徑,我只舉幾個地方的例子即可,剩下就交給讀者自行練習了。

<!-- Custom fonts for this template-->
<link href="{% static 'bootstrap/css/sb-admin.min.css' %}" rel="stylesheet">

上方為最初的路徑,需要改成下面路徑:在我的專案static裡面,我額外增加bootstrap檔案來分類,可自行建立分類。

<!-- Custom fonts for this template-->
<link href="{% static 'bootstrap/vendor/fontawesome-free/css/all.min.css' %}" rel="stylesheet" type="text/css">

有可能會產生出無法顯示的問題,可以參考下面的stackoverflow

結束….

[補充]

你可以自己在思考看看下面問題:

  1. django template應該可以全部使用base.html來接重複的頁面部分問題,用來減少重複程式碼的部分。
  2. 承1,django template tag也可以來使用{% extends ‘base.html’ %}, {% load static %}, {% include ‘index.html’ %}, {% block content %}{% endblock %}…等等。

如果你覺得文章很棒或有幫助到您,不妨幫我點個拍手吧! 謝謝…

--

--