Programmers/데브코스 인공지능

[프로그래머스 스쿨 AI] Weak 5 django

1. django 사용하기

1. 가상환경 만들기(그냥 말만 가상환경 원래 시스템이랑 다를거 없음)

# 터미널
pip install virtualenv

virtualenv venv

source venv/Scripts/activate

2. django 설치

pip install django

django-admin startproject web_dj

cd web_dj

python manage.py runserver

3. 파일가보기 

 

web_dj─┬─ __pycache__ ── 시스템파일들 있음
              ├─ __init__.py # 웹프로젝트 인식되게하는
              ├─ asgi.py     # 서버에서 작동하는 파일
              ├─ settings.py # 설정사항 반형 여기서 디버그 모드 할수 있음
              ├─ urls.py     # 주소 관리하는곳
              └─ wsgi.py    # 서버에서 작동하는 파일
manage.py

4. app 추가하기

# 터미널

#위치는 manage.py있는곳에서
django-admin startapp main

1.view 파일

web_dj─┬─ __pycache__ ── 시스템파일들 있음
              ├─ __init__.py # 웹프로젝트 인식되게하는
              ├─ asgi.py     # 서버에서 작동하는 파일
              ├─ settings.py # 설정사항 반형 여기서 디버그 모드 할수 있음
              ├─ urls.py     # 주소 관리하는곳
              └─ wsgi.py    # 서버에서 작동하는 파일
main   ─┬─ migration ── 시스템파일들 있음
              ├─ __init__.py # 웹프로젝트 인식되게하는
              ├─ admin.py    
              ├─ apps.py 
              ├─ models.py  
              ├─ tests.py     
              └─ views.py    # html 연동시키는곳

manage.py

2. settings.py app 추가해주기

"""
Django settings for web_dj project.

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

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-#8n)s9ls9z_q7kln$o+og6pheuscf)i++30h^sgde0y6hw2(^^'

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

 

 

5.관리자 계정 추가하기

#터미널 
python manage.py migrate # 만들어진 기본설정 추가하기 처음에 기본설정이 연결되있지않음
python manage.py createsuperuser # 슈퍼유저 만들기
유저이름 적으라함 : liebespaar93
이메일 적으라함 : liebespaar93@naver.com
비밀번호 적으라함 : 0000
비밀번호 다시적으라함 : 0000

주소 "127.0.0.1:8000/admin" 으로 가보자

2. django  웹페이지 보여주기

1.실행할 app 폴더(main)에 templates를 만들어준다

그안에 index.html을 만들어준다

<index.html 코드 추가하기>

 

 

2. main - view 파일에 html 실행 함수를 하나 만들어준다

from django.shortcuts import render

# Create your views here.
def main(request):
    return render(request,"index.html", {})

3. web_dj - settings에 template폴더를 추가해준다 

BASE_DIR 의 기준점을 이용하여 추가해준다

<setting 파일 코드 가져온다>

전문적 함수

"""
Django settings for web project.

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

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
import os
# 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-&u&nwiq+z)$xlk0k8g#eyysi!*1y3ztn-i9imr$mt07spjp#_w'

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

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 = 'web.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR,'main','templates')],
        '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 = 'web.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 = 'UTC'

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'

4. urls.py 에 주소를 추가해준다

"""web_dj URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from main.views import main

urlpatterns = [
    path('', main),
    path('admin/', admin.site.urls),
]

3. django html에 python 전해주기

1. render 에 딕셔너리 형태로 전해준다{ "html_look" : python_data }

{{ html_look }}

 

2. 함수 사용하기

{% for i in html_look %}

이런식

{% endfor %}

 

 

4. 영상