[Django] Memo to create an environment of Django + MySQL + Vue.js [Python]

github https://github.com/foasho/Django_Vue_template

System configuration

・ Django version.2.1.0 ・ Vue.js ・ MySQL

django-admin startproject config .
python manage.py startapp accounts

Initial setting

Added to APPS

config/setting.py


INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    
    "accounts.apps.AccountsConfig",
]

Set language and time zone to Japanese specifications

config/setting.py


LANGUAGE_CODE = 'ja'

TIME_ZONE = 'Asia/Tokyo'

Set up MySQL in your Django database

pip install pymysql
pip install python-dotenv

Edit manage.py (add MySQL)

manage.py


import pymysql
pymysql.install_as_MySQLdb()

Creating an .env file in config

config/.env


DB_NAME = XXXXX
DB_PWD = XXXXX
DB_USER = XXXXX
DB_HOST = XXXXX

Edit setting.py

config/setting.py


from os.path import join, dirname
from dotenv import load_dotenv

config/setting.py


dotenv_path = join(dirname(__file__), '.env')
load_dotenv(dotenv_path)
DB_NAME = os.environ.get("DB_NAME")
DB_PWD = os.environ.get("DB_PWD")
DB_USER = os.environ.get("DB_USER")
DB_HOST = os.environ.get("DB_HOST")

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': DB_NAME,#Database name
        'USER': DB_USER,#username
        'PASSWORD': DB_PWD,#password
        'HOST': DB_HOST,#Local host etc.
        'PORT': '3306',#Connection port
    }
}

Set the logger

config/settings.py


#Logging settings
LOGGING = {
    "version": 1,
    "disavle_existing_loggers": False,
    
    #Logger settings
    "logger":{
        "django": {
            "handlers": ["console"],
            "lebel": "INFO",
        }
    },
    #Logger to use the accounts app
    "diary": {
        "handlers": ["console"],
        "level": "DEBUG",
    },
    #Handler settings
    "handlers": {
        "console": {
            "level": "DEBUG",
            "class": "logging.StreamHandler",
            "formatter": "dev"
        },
    },
    #Formatter settings
    "formatters": {
        "dev": {
            "format": "\t".join([
                "%(asctime)s",
                "[%(levelname)s]",
                "%(pathname)s(Line:%(lineno)d)",
                "%(message)s"
            ])
        },
    },
}

Set the routing and access index.html

config/urls.py


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

urlpatterns = [
    path('admin/', admin.site.urls),
    path("", include("accounts.urls"))
]

Create new file: accounts / urls.py

accounts/urls.py


from django.urls import path
from . import views

app_name = "accounts"

urlpatterns = [
    path("", views.IndexView.as_view(), name="index")
]

Create a new directory "templates" Created in accounts / templates

Create a new file index.html

accouts/templates/index.html


<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>top page</title>
</head>
<body>
    <h1>Hello World</h1>
</body>
</html>

Verification

python manage.py runserver

Reflect the Bootstrap template

Add static folder

Download Bootstrap (https://startbootstrap.com/themes/one-page-wonder)

Create a new static folder directly under the project

Put the downloaded BootStrap in a static folder

├── accounts
├── config
├── static
|       ├── css
|       ├── img
|       └── vender
├── manage.py

Set views.py to display html.

accounts/views.py


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

class IndexView(generic.TemplateView):
    template_name = "index.html"

Set the location where the static folder is located

config/settings.py


STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
)

Create a common base.html on each page

accounts/templates/base.html


{% load static %}

<html lang="ja">

  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>{% block title %}{% endblock %}</title>

    <!-- Bootstrap core CSS -->
    <link href="{% static 'vendor/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet">

    <!-- Custom fonts for this template -->
    <link href="https://fonts.googleapis.com/css?family=Catamaran:100,200,300,400,500,600,700,800,900" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Lato:100,100i,300,300i,400,400i,700,700i,900,900i" rel="stylesheet">

    <!-- Custom styles for this template -->
    <link href="{% static 'css/one-page-wonder.min.css' %}" rel="stylesheet">

    <!-- My style -->
    <link rel="stylesheet" type="text/css" href="{% static 'css/mystyle.css' %}">

    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    <script src="https://unpkg.com/vue"></script>

    {% block head %}{% endblock %}
  </head>

  <body>
	<div id="wrapper">
        <!--Navi header-->
        <nav class="navbar navbar-expand-lg navbar-dark navbar-custom fixed-top">
          <div class="container">
            <a class="navbar-brand" href="{% url 'accounts:index' %}">TITLE</a>
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
              <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarResponsive">
              <ul class="navbar-nav mr-auto">
                <li class="nav-item {% block active_inquiry %}{% endblock %}">
                  <a class="nav-link" href="#">INQUIRY</a>
                </li>
              </ul>
              <ul class="navbar-nav ml-auto">
                <li class="nav-item">
                  <a class="nav-link" href="#">Sign Up</a>
                </li>
                <li class="nav-item">
                  <a class="nav-link" href="#">Log In</a>
                </li>
              </ul>
            </div>
          </div>
        </nav>

        {% block contents%}{% endblock %}

        <!-- Footer -->
        <footer class="py-5 bg-black">
          <div class="container">
            <p class="m-0 text-center text-white small">&copy;Foa TemplatesCode 2020</p>
          </div>
          <!-- /.container -->
        </footer>

        <!-- Vue.js JavaScript -->
        {% block scripts%}{% endblock %}

        <!-- Bootstrap core JavaScript -->
        <script src="{% static 'vendor/jquery/jquery.min.js' %}"></script>
        <script src="{% static 'vendor/bootstrap/js/bootstrap.bundle.min.js' %}"></script>
  	</div>
  </body>

</html>

Also edit index.html like that

accounts/templates/index.html


{% extends 'base.html' %}
{% load static %}

{% block title %}TITLE --Subtitle{% endblock %}

{% block contents %}
<div id="indexapp">
  <header class="masthead text-center text-white">
    <div class="masthead-content">
      <div class="container">
        <h1 class="masthead-heading mb-0">[[ title ]]</h1>
        <h2 class="masthead-subheading mb-0">SubTitle</h2>
        <a href="#" class="btn btn-primary btn-xl rounded-pill mt-5">LOG IN</a>
      </div>
    </div>
    <div class="bg-circle-1 bg-circle"></div>
    <div class="bg-circle-2 bg-circle"></div>
    <div class="bg-circle-3 bg-circle"></div>
    <div class="bg-circle-4 bg-circle"></div>
  </header>
  <div class="py-5 text-white" style="background-image: linear-gradient(to bottom, rgba(0, 0, 0, .75), rgba(0, 0, 0, .75)), url(https://static.pingendo.com/cover-bubble-dark.svg);  background-position: center center, center center;  background-size: cover, cover;  background-repeat: repeat, repeat;">
    <div class="container">
      <div class="row">
        <div class="p-3 col-md-8 col-lg-6 ml-auto text-right text-white">
          <p class="lead">"I throw myself down among the tall grass by the trickling stream; and, as I lie close to the earth, a thousand unknown plants are noticed by me: when I hear the buzz of the little world among the stalks."</p>
          <p><b>Johann Goethe</b><br><small>CEO and founder</small></p>
        </div>
      </div>
    </div>
  </div>
  <div class="py-5" style="background-image: linear-gradient(to left bottom, rgba(189, 195, 199, .75), rgba(44, 62, 80, .75)); background-size: 100%;">
    <div class="container">
      <div class="row">
        <div class="text-center mx-auto col-md-12">
          <h1 class="text-white mb-4">Testimonials</h1>
        </div>
      </div>
      <div class="row">
        <div class="col-lg-4 col-md-6 p-3">
          <div class="card">
            <div class="card-body p-4">
              <div class="row">
                <div class="col-md-4 col-3"> <img class="img-fluid d-block rounded-circle" src="https://static.pingendo.com/img-placeholder-2.svg"> </div>
                <div class="d-flex  col-md-8 flex-column justify-content-center align-items-start col-9">
                  <p class="mb-0 lead"> <b>J. W. Goethe</b> </p>
                  <p class="mb-0">Co-founder</p>
                </div>
              </div>
              <p class="mt-3 mb-0">I throw myself down among the tall grass by the trickling stream; and, as I lie close to the earth, a thousand unknown plants are noticed by me: when I hear the buzz of the little world.</p>
            </div>
          </div>
        </div>
        <div class="col-lg-4 col-md-6 p-3">
          <div class="card">
            <div class="card-body p-4">
              <div class="row">
                <div class="col-md-4 col-3"> <img class="img-fluid d-block rounded-circle" src="https://static.pingendo.com/img-placeholder-1.svg"> </div>
                <div class="d-flex  col-md-8 flex-column justify-content-center align-items-start col-9">
                  <p class="mb-0 lead"> <b>G. W. John</b> </p>
                  <p class="mb-0">CEO &amp; founder</p>
                </div>
              </div>
              <p class="mt-3 mb-0" >I lie close to the earth, a thousand unknown plants are noticed by me: when I hear the buzz of the little world among the stalks, and grow familiar with the countless indescribable forms of the insects and flies.</p>
            </div>
          </div>
        </div>
        <div class="col-lg-4 p-3">
          <div class="card">
            <div class="card-body p-4">
              <div class="row">
                <div class="col-md-4 col-3"> <img class="img-fluid d-block rounded-circle" src="https://static.pingendo.com/img-placeholder-3.svg"> </div>
                <div class="d-flex  col-md-8 flex-column justify-content-center align-items-start col-9">
                  <p class="mb-0 lead"> <b>J. G. Wolf</b> </p>
                  <p class="mb-0">CFO</p>
                </div>
              </div>
              <p class="mt-3 mb-0">Oh, would I could describe these conceptions, could impress upon paper all that is living so full and warm within me, that it might be the mirror of my soul, as my soul is the mirror of the infinite God!</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="py-5 text-center">
    <div class="container">
      <div class="row">
        <div class="mx-auto col-md-8">
          <h1>{{ this.title }}</h1>
          <p class="mb-4"> Oh, would I could describe these conceptions, could impress upon paper all that is living so full and warm within me, that it might be the mirror of my soul, as my soul is the mirror of the infinite God! O my friend -- but it is too much for my strength -- I sink under the weight of the splendour of these visions!</p>
          <div class="row text-muted">
            <div class="col-md-2 col-4 p-2"> <i class="d-block fa fa-angellist fa-3x"></i> </div>
            <div class="col-md-2 col-4 p-2"> <i class="d-block fa fa-cc-visa fa-3x"></i> </div>
            <div class="col-md-2 col-4 p-2"> <i class="d-block fa fa-empire fa-3x"></i> </div>
            <div class="col-md-2 col-4 p-2"> <i class="d-block fa fa-paypal fa-3x"></i> </div>
            <div class="col-md-2 col-4 p-2"> <i class="d-block fa fa-rebel fa-3x"></i> </div>
            <div class="col-md-2 col-4 p-2"> <i class="d-block fa fa-first-order fa-3x"></i> </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
{% endblock %}

{% block scripts %}
<script src="{% static 'js/index_vue.js' %}"></script>
{% endblock %}

Incorporate Vue.js

Create a file and change the Title dynamically

Created in a new folder "js" in static Create index.js in js Not to be confused with Django's system delimiters: ['[[',']]'] is important

static/js/index.js


var app = new Vue({
    delimiters: ['[[', ']]'],
    el: '#indexapp',
    data: {
        title: "TestTitle"
    },
})

Run

python manage.py runserver

Recommended Posts

[Django] Memo to create an environment of Django + MySQL + Vue.js [Python]
A memo to create a virtual environment (venv) before Django
How to develop in a virtual environment of Python [Memo]
[Cloud9] Try to build an environment with django 1.11 of Python 3.4 without understanding even 1 mm
Overview of Python virtual environment and how to create it
[Docker] Build an environment of python (Flask) + GraphQL (graphene) + MySQL (sqlalchemy)
I tried to create an environment of MkDocs on Amazon Linux
Various ways to create an array of numbers from 1 to 10 in Python.
How to create an NVIDIA Docker environment
Create an OpenCV3 + python3 environment on OSX
Build Python + django + nginx + MySQL environment using docekr
For beginners to build an Anaconda environment. (Memo)
How to create a Python virtual environment (venv)
Create Nginx + uWSGI + Python (Django) environment with docker
[Python] Create an asynchronous task execution environment + monitoring environment
Introduction to Python "Re" 1 Building an execution environment
How to build an environment for using multiple versions of Python on Mac
My python environment memo
Unification of Python environment
Create a Python environment
Connect python to mysql
[Memo] Django development environment
The wall of changing the Django service from Python 2.7 to Python 3
Memo to create your own Box with Pepper's Python
A memo connected to HiveServer2 of EMR with python
[Blender x Python] How to create an original object
Memo of deploying Django × Postgresql on Docker to Heroku
Build a Python virtual environment using venv (Django + MySQL ①)
To myself as a Django beginner (4) --Create a memo app--
[Python] If you suddenly want to create an inquiry form
Introduction to Python Django (2) Win
Create an API with Django
Django development environment construction memo
How to create an instance of a particular class from dict using __new__ () in python
Initial setting of environment using Docker-compose + Django + MySQL + Nginx + uwsgi
Minimum Makefile and buildout.cfg to create an environment with buildout
Shell to create django project
Memo of python + numpy/scipy/pandas/matplotlib/jupyterlab environment construction on M1 macOS (as of 2020/12/24)
[Memo] Construction of cygwin environment
I'm trying to create an authentication / authorization process with Django
Create a Todo app with Django ① Build an environment with Docker
[MEMO] [Development environment construction] Python
An introduction to Python Programming
Create an executable file (EXE) by PyInstaller in a hybrid environment (Nimporter) of Python + Nim
[Python Kivy] How to create an exe file with pyinstaller
Python environment construction and SQL execution example to DB and memo of basic processing for statistics 2019
Environment construction of python2 & 3 (OSX)
How to easily create an environment where python code runs on Jupyter without polluting the local environment
Memo to switch between python2 series and 3 series in anaconda environment of mac (win is also added)
Create another version of Python conda environment with one command line
How to know the internal structure of an object in Python
Try to create a python environment with Visual Studio Code & WSL
I tried to create a list of prime numbers with python
How to create a heatmap with an arbitrary domain in Python
Create an environment for Django x Apache x mod_wsgi with Vagrant (Ubuntu 16.04)
When creating an environment that uses python django on Ubuntu 12.04 LTS
How to create a large amount of test data in MySQL? ??
[For Python] Quickly create an upload file to AWS Lambda Layer
Learn how to use Docker through building a Django + MySQL environment
Environment construction of python and opencv
Python environment construction memo on Windows 10