LoginSignup
1
3

More than 3 years have passed since last update.

【Django】Djangoのなんとなくスルーしていた個所をテストで詳らかにしてみる

Last updated at Posted at 2020-10-04

目的

①settings.pyにある謎の変数とかをコンソールに出してふーんてなる。
②パスワードとか隠す

OS等

Windows 10 Home

環境構築

PyCharmタイトルにて「新規プロジェクトの作成」クリック。
01.JPG

タイトルをつける。今回は"djangostudy"とする。名前を付けたら「作成」をクリック。
02.JPG

「ファイル」→「設定」(Ctrl + Alt + S) で設定画面を開き、「プロジェクト・インタープリター」を選択。
03.JPG

右にある「+」のとこをクリック。
04.JPG

使用可能なパッケージ一覧が出てくる。検索バーにdjangoと入力して出てきたやつを選択。「パッケージのインストール」を押下してちょっと待つ。
image.png

なんか増えてたら成功。下にもinstalled successfullyと出てるのでよし。
06.JPG

下のほうに「ターミナル」というのがあるのでそこをクリック。ターミナルを出す。
image.png

ターミナルに入力する。

コンソール
# "Verification"という名前のプロジェクトを作成する。
(venv) C:\*****\*****\PycharmProjects\djangostudy> django-admin startproject Verification

Verificationというフォルダが作成された。
image.png

ターミナルに以下を入力する。

コンソール
# Verificationフォルダ内の"manage.py"に用があるので移動する。
(venv) C:\*****\*****\PycharmProjects\djangostudy> cd Verification

# webサーバーを起動し、Verificationプログラムを実行する。
(venv) C:\*****\*****\PycharmProjects\djangostudy\Verification> python manage.py runserver

ターミナルの表示がこんなんなるので、青くなってるurlをクリックする。
http://127.0.0.1:8000
image.png

ロケットがでてたら成功。webサーバーはターミナルをCtrl + c で停止できる。
image.png

ターミナルに以下を入力する。

コンソール
# "testapp"という名前のアプリケーションを作成する。
(venv) C:\ ~ \Verification> python manage.py startapp testapp

"testapp"というフォルダが作成された。
image.png

settings.pyの中身

Verification/settings.pyの中身。なんのこっちゃわからん。

settings.py
"""
Django settings for Verification project.

Generated by 'django-admin startproject' using Django 3.1.2.

For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
# セキュリティなんちゃらと上に書いてあるので隠します。
SECRET_KEY = 'hogehogehogehogehogehogehogehogehogehogehogehogeho'
        
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

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

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'Verification.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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',
            ],
        },
    },
]

WSGI_APPLICATION = 'Verification.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/

STATIC_URL = '/static/'

settings.pyの変数をprintしてターミナル上に出してみる

settings.py BASE_DIR
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

早速なんのこっちゃわからんBASE_DIRを表示してみる

以下の関数をsettings.pyに追加

settings.py
def verifyConst(varname, var):
# 変数:変数の中身をターミナル上に表示する。
    varname += ' : '
    print(varname + str(var))

# BASE_DIR の中身
verifyConst('__file__', __file__)
verifyConst('Path(__file__)', Path(__file__))
verifyConst('Path(__file__).resolve()', Path(__file__).resolve())
verifyConst('Path(__file__).resolve().parent', Path(__file__).resolve().parent)
verifyConst('BASE_DIR', BASE_DIR)
print()

結果
image.png

BASE_DIR = Path(file).resolve().parent.parent
BASE_DIRとはmanage.pyファイルがおかれている場所だそうで、それを求めるために色々やってるみたいです。
Path(file).resolve():settings.pyのパス
Path(file).resolve().parent:settings.pyの親フォルダ
Path(file).resolve().parent.parent: settings.pyの親フォルダの親フォルダ

.parentというのが親フォルダを表すようだ。

1
3
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
1
3