Python web模版Django-25 在Django中載入css例項 (基於23,對24的index.html進一步修改 )
阿新 • • 發佈:2018-11-14
在前面Django-24的筆記中,對index.html用Django-bootstrap3進行了改造簡化,Django-bootstrap3中引用的css,js其實還是Bootstrap的CDN。CDN雖然方便,但以後帶來的問題也是可以遇見的,就是CDN伺服器關了的話,我們開發的網頁就沒有了樣式。所以還是要嘗試將相關CSS,JS部署到自己放心的地方。
這裡結合Django-23筆記中的方法,將signin.css移到本專案目錄中。
step1: 建立目錄放置css檔案,在sign->templates下建立static資料夾,再在其下建立css和images資料夾,如果有需要可以建立javascript資料夾。
step2: 在settings.py檔案中設定templates和靜態路徑
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,"sign/templates").replace("\\", "/"), os.path.join(BASE_DIR, 'templates').replace("\\", "/")], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, },]
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'sign/templates/static')
STATICFILES_DIRS = (
('css', os.path.join(STATIC_ROOT, 'css')),
('images', os.path.join(STATIC_ROOT, 'images')),
)
step3: 修改urls.py檔案
在urls.py開頭加上一句:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
- 1
在urls.py的最後加上以下內容:
urlpatterns += staticfiles_urlpatterns()
step4: 在pycharm中用collectstatic命名
step5: 修改index.html檔案
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
{% load bootstrap3 %}
{% bootstrap_css %}
{% bootstrap_javascript %}
{% bootstrap_messages %}
<!-- Custom styles for this template -->
<!--link href="../signin.css" rel="stylesheet"-->
<link href="/static/css/signin.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="container">
<form class="form-signin" action="/login_action/" method="post">
<h2 class="form-signin-heading">釋出會管理</h2>
<label for="inputUsername" class="sr-only">username</label>
<input type="text" id="inputUsername" name="username" class="form-control" placeholder="username" required autofocus>
<label for="inputPassword" class="sr-only">password</label>
<input type="password" id="inputPassword" name="password" class="form-control" placeholder="password" required>
<button class="btn btn-lg btn-primary btn-block" type="submit" id="btn">登入</button>
{{wronglyInput}}<br>
{% csrf_token %}
</form>
</div> <!-- /container -->
</body>
</html>
step6: 執行看看效果,執行正常,說明本地的css載入成功