Django/inflearn

템플릿 기본(변수 넘기기)

곽수진 2022. 9. 20. 01:16
반응형

"""
Django settings for firstdjango project.

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

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

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/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.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-=&v14*#%e)$a-0&+k85e0w@c3jj5k-2ab$2^7=g_tpc_et)%(&'

# 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',
    'first',
]

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 = 'firstdjango.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 = 'firstdjango.wsgi.application'


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

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


# Password validation
# https://docs.djangoproject.com/en/3.2/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.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Asia/Seoul'

USE_I18N = True

USE_L10N = True

USE_TZ = True


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

STATIC_URL = '/static/'

# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

 settings.py에 템플릿 파일을 인식할 수 있도록 웹 앱을 INSTALLED_APPS에 추가하고 TIME_ZONE을 우리나라 시간에 맞도록 'Asia/Seoul'로 변경함

 

 

from django.shortcuts import render
from django.http import HttpResponse

from django.template import loader
from datetime import datetime

# Create your views here.
def index(request):
    template = loader.get_template('index.html')
    now = datetime.now()
    context = {
        'current_date' : now
    }
    return HttpResponse(template.render(context, request))


def select(request):
    message = '수 하나를 입력해주세요.'
    return HttpResponse(message)


def result(request):
    message = '추첨 결과입니다.'
    return HttpResponse(message)

▶ django.template의 loader를 임포트하고 template을 연결

▶ index 메소드를 생성해 template으로 넘겨줄 정보를 정의함

 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <p>Hello World!</p>
    <p>{{ current_date }}</p>
    <p>{{ current_date|date:"Y년 m월 d일 H시 i분 s초" }}</p>
</body>
</html>

HTML 파일과 views.py를 연동하기 위해 first(웹 앱 폴더) 내에 templates 폴더를 생성하고 index.html 파일을 만듦

▶ Django 템플릿 언어를 이용해 current_date로 넘어온 변수를 표시

    → 기존에 내장된 date 필터를 사용해 표시 형식을 지정할 수 있음

 

 

반응형

'Django > inflearn' 카테고리의 다른 글

스태틱 파일 띄우기  (0) 2022.09.27
템플릿 조건 처리  (0) 2022.09.25
URL 매핑 규칙  (0) 2022.09.19
여러 페이지 띄우기  (0) 2022.09.18
간단한 웹 페이지 띄우기  (0) 2022.09.17