Django | Build a Dashboard with Django and Bootstrap: Part 1

This is Part 1 of Building a Dashboard with Django and Bootstrap:

Inhaltsverzeichnis

Introduction

Building a complete web app isn’t always an easy task. Designing and Implementing on both sides (backend and front-end) requires mostly a lot of knowledge. So, why don’t using tools or framework, which helps and makes our life easier. Django is one of these frameworks:

Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development

So, let’s get started.

Create project

For subsequent steps, we will remember our starting directory

❯ DASHBOARD_ROOT=$(pwd)
❯ echo $DASHBOARD_ROOT
... here you will see your current folder...

First step is to create our main Django project

❯ django-admin startproject dashboard
❯ mv dashboard project
❯ cd project
❯ python manage.py migrate
❯ python manage.py runserver 8080
...

Starting development server at http://127.0.0.1:8080/
Quit the server with CTRL-BREAK.

View current project in browser

Create first apps

❯ mkdir -p apps/core
❯ python manage.py  startapp Core apps/core

❯ mkdir -p apps/frontend
❯ python manage.py startapp Frontend apps/frontend

The folder structure should look like this:

Add new apps to project

Modify name in apps/core/apps.py

class CoreConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'apps.core'

Modify name in apps/frontend/apps.py

class FrontendConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'apps.frontend'

Modify dashboard/settings.py

INSTALLED_APPS = [
   ...

    'apps.core',
    'apps.frontend',
]

Modify dashboard/urls.py

from django.contrib import admin
from django.urls import path

import apps.frontend.views as views

urlpatterns = [
    path('', views.IndexView.as_view(), name='index'),
    path('admin/', admin.site.urls),
]

Create view

Modify view in apps/frontend/views.py

from django.shortcuts import render
from django.views import generic


class IndexView(generic.TemplateView):
    """
    IndexView:
    """
    module = 'indexView'
    template_name = 'frontend/index.html'

Create template for frontend View

Create template file apps/frontend/templates/frontend/index.html

<h1>
Frontend: Let's get started
</h1>

Add template folder to configuration

In dashboard/settings.py, add template folder to TEMPLATES

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates'],
]

View current project in browser

Current folder Structure

So far, we have the following folder structure

Prepare for administrate your project

Create admin user

❯ python manage.py createsuperuser
Username (leave blank to use 'user'): admin
Email address: admin@localhost
Password: 
Password (again): 
Superuser created successfully.

Add Bootstrap support

Download requires files for Bootstrap, jQuery and PopperJS.

Or download this prepared archiv and unzip the files unter dashboard.

Run the scripts in $DASHBOARD_ROOT

Hint: You need to install PowerShell before running the scripts.

> cd $DASHBOARD_ROOT
> ./download_bootstrap.ps1
> ./download_jquery.ps1
> ./download_popperjs.ps1

download_bootstrap.ps1

#!/usr/bin/env pwsh

$ROOT = Split-Path -Parent $PSSCRIPTROOT

$global:ProgressPreference  = 'SilentlyContinue'  
$response = Invoke-WebRequest https://getbootstrap.com/ 
$downloadlink = $response.links | Where-Object { $_.href -like "*download/" } | foreach-object { $_.href } | select-object -first 1 
$downloadpage = Invoke-WebRequest https://getbootstrap.com$downloadlink

$dist_download_url = $downloadpage.links | where-object { $_.href -like "*-dist.zip" } | foreach-object { $_.href }
$dist_version      = $dist_download_url.split("/")[-2].replace("v","")
$dist_zip          = "$ROOT\${dist_version}.zip"

Write-Host "Download $dist_zip from $dist_download_url"
Invoke-WebRequest $dist_download_url -O $dist_zip

Write-Host "Unpack to assets\vendor\bootstrap\${dist_version}"

$fldr_bootstrap = "project\dashboard\static\assets\vendor\bootstrap"

if (Test-Path -Path $fldr_bootstrap) {
    Remove-Item -recurse -force           $fldr_bootstrap
}

New-Item -type directory                  $fldr_bootstrap > $null 
Expand-Archive $dist_zip -destinationpath $fldr_bootstrap

Move-Item $fldr_bootstrap\bootstrap* $fldr_bootstrap\${dist_version}

$global:ProgressPreference  = 'Continue'

download_jquery.ps1

#!/usr/bin/env pwsh

$ROOT = Split-Path -Parent $PSSCRIPTROOT

$version = "3.7.0"

$url_base = "https://code.jquery.com"

$destination = "project\dashboard\static\assets\vendor\jquery\$version\js"

Write-Host "Prepare  destination $destination"
if (Test-Path -Path $destination) {
    Remove-Item -recurse -force           $destination > $null
}

New-Item -type directory                  $destination > $null 

Invoke-WebRequest $url_base/jquery-${version}.js      -O $destination/jquery-${version}.js
Invoke-WebRequest $url_base/jquery-${version}.min.map -O $destination/jquery-${version}.min.map

download_popperjs.ps1

#!/usr/bin/env pwsh

$ROOT = Split-Path -Parent $PSSCRIPTROOT

$version = "2.11.8"

$url_base = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/${version}/umd/"

$destination = "project\dashboard\static\assets\vendor\popperjs\$version\js"

Write-Host "Prepare  destination $destination"
if (Test-Path -Path $destination) {
    Remove-Item -recurse -force           $destination > $null
}

New-Item -type directory                  $destination > $null 

Invoke-WebRequest $url_base/popper.js -O  $destination/popper.js

Finally, the folder structure should look like this:

Create site templates in dashboard/templates/site

Add templates path to settings

File dashboard/settings.py

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            BASE_DIR / '/dashboard/templates',
        ],
        ...

Add static path to settings

File dashboard/settings.py

Add as first line

import os

Then add / replace at STATIC_URL=...

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

Modify frontend view template

File dashboard/apps/frontend/templates/index.html






<main>
	<div class="p-5 mb-4 bg-body-tertiary rounded-3">
		<div class="container-fluid py-5">
			<h1 class="display-5 fw-bold">Custom jumbotron</h1>
			<p class="col-md-8 fs-4">Using a series of utilities, you can create this jumbotron, just like the one in
				previous versions of Bootstrap. Check out the examples below for how you can remix and restyle it to
				your liking.</p>
			<button class="btn btn-primary btn-lg" type="button">Example button</button>
		</div>
	</div>
	</div>
</main>




File dashboard/apps/frontend/templates/site/base.html

<!DOCTYPE html>
<html>

<head>
    <title>
    <link rel="stylesheet" href="
</head>

<body>

    <nav class="navbar navbar-expand-md navbar-dark bg-dark mb-4">
        <div class="container-fluid">
          <a class="navbar-brand" href="#">Navigation</a>
          <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
          </button>
          <div class="collapse navbar-collapse" id="navbarCollapse">
            <ul class="navbar-nav me-auto mb-2 mb-md-0">
              <li class="nav-item"><a class="nav-link active" aria-current="page" href="#">Home</a></li>
              <li class="nav-item"><a class="nav-link" href="polls">Polls</a>
              </li>
            </ul>
          </div>
        </div>
      </nav>

    <div class="container">
        
        
    </div>

    <script src="
</body>

</html>

View current status of project

Final Result

The final result could be found here.

Add dashboard from an existing template

For a first start, we will use this sb-admin-2 dashboard template from here:

Download required files

Bootstrap templates consist of at least 3 different types of files

  • main index.html page, responsible for collection all elements and set up your page
  • CSS files defining the style of your page
  • JavaScript files, containing needed frameworks and code

So, first start by downloading the sample template from here. Be sure, you start in our project root folder:

❯ cd $DASHBOARD_ROOT
❯ git clone https://github.com/BlackrockDigital/startbootstrap-sb-admin-2 install/sb-admin-2

Next, find out, what we need for our template in addition to the file index.html

❯ cd install/sb-admin-2
❯ grep -E "<(link|script)" index.html | grep -E "(href|src)="
  <link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
  <link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet">
  <link href="css/sb-admin-2.min.css" rel="stylesheet">
  <script src="vendor/jquery/jquery.min.js"></script>
  <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
  <script src="vendor/jquery-easing/jquery.easing.min.js"></script>
  <script src="js/sb-admin-2.min.js"></script>
  <script src="vendor/chart.js/Chart.min.js"></script>
  <script src="js/demo/chart-area-demo.js"></script>
  <script src="js/demo/chart-pie-demo.js"></script>

That’s a lot of additional files.

To keep the file structure consistent, these files should be stored under the dashboard/static folder (same as the bootstrap files before).

To achieve this, there are two possibilities:

  • Create desired folder and copy each of the source files to the destination folder
  • Copy the complete static folder from the Github Repository for this post.

We use the second option to keep the focus on creating our dashboard.

So, first, clone the repository:

cd $DASHBOARD_ROOT/install
https://github.com/r14r/Django_Dashboard-with-Django-and-Bootstrap

Then, copy the requred files

cd $DASHBOARD_ROOT

cp -R install/Django_Dashboard-with-Django-and-Bootstrap/project/dashboard/static project/dashboard
cp -R install/Django_Dashboard-with-Django-and-Bootstrap/project/dashboard/templates dashboard

Having everything needed for the dashboard template, the next step is to modify the front-end template

File dashboard/apps/frontend/templates/frontend/index.html

View current project in browser

Perfect. We are done with the basic setup.

Still some work to do, because our dashboard is only a static dashboard. All content is programmed in the dashboard template file dashboard/templates/site/sb-admin-2/base.html

For example, look at the cards with the earnings at the top:

To achieve a more dynamic content, we need to move the desired parts of the dashboard from the template file to the front-end view file.

This will be described in the next step: Part 2: Prepare for dynamic content

Pages: 1 2