6
10

More than 1 year has passed since last update.

DjangoでBootstrap5

Last updated at Posted at 2023-01-23

DjangoでBootstrapを使う時にすること

概要

 Djangoのアプリを作り始めるときに行うことの一つ、Bootstrapの設定について記します。
 対象OSはWindowsです。
 VisualStudioCode(以下 VSCode)を使用します。
 以下の手順で作成します。

  1. django-bootstrapのインストール
  2. settings.pyへ登録
  3. ベーステンプレートを作る
  4. テンプレートの作成
  5. views.pyの作成

 環境の作成は以下を参照して下さい。

 事前に以下の設定を行っているものとします。

django-bootstrapのインストール

 django-bootstrap5 を仮想環境内にインストールします。

(venv) PS C:\ws\sample> pip install django-bootstrap5
Collecting django-bootstrap5
  Downloading django_bootstrap5-22.2-py3-none-any.whl (24 kB)
Requirement already satisfied: Django>=3.2 in c:\ws\sample\venv\lib\site-packages (from django-bootstrap5) (4.1.5)
Requirement already satisfied: asgiref<4,>=3.5.2 in c:\ws\sample\venv\lib\site-packages (from Django>=3.2->django-bootstrap5) (3.6.0)
Requirement already satisfied: tzdata in c:\ws\sample\venv\lib\site-packages (from Django>=3.2->django-bootstrap5) (2022.7)
Requirement already satisfied: sqlparse>=0.2.2 in c:\ws\sample\venv\lib\site-packages (from Django>=3.2->django-bootstrap5) (0.4.3)
Installing collected packages: django-bootstrap5
Successfully installed django-bootstrap5-22.2

settings.pyへ登録

 django-bootstrap5をsettings.pyへ登録します。

project\setings.py
# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
+    'django_bootstrap5',
    'app01',
]

ベーステンプレートを作る

 これから作成するhtmlの共通部分をベーステンプレートとして作成します。
 これ以降作成するテンプレートはこのベーステンプレートを継承して作成します。

app01\templates\app01\base.html
{% load django_bootstrap5 %}

<!DOCTYPE html>
<html lang="ja">
  <head>
    <title>{{title}}</title>
    <meta charset="utf-8">
    {% bootstrap_css %}
    {% bootstrap_javascript %}
  </head>
  <body>
    {% block content %}
    {% endblock content %}
  </body>
</html>

テンプレートの作成

 ベーステンプレートを継承するようにテンプレートファイルへ記載します。

app01\templates\app01\index.html
{% extends 'app01/base.html' %}
{% block content %}
  <div class="bg-primary text-white">
    {{text}}
  </div>
{% endblock content %}

views.pyの作成

 ベーステンプレートにタイトルをつけたのでその分の記載を追加します。

app01\views.py
from django.shortcuts import render

# Create your views here.

def index(request):
    message = {
        'title':'app01',
        'text':'Hello',
    }
    return render(request, 'app01/index.html', message)

これでBootstrapが使えるようになります。

image.png

6
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
10