본문 바로가기

데이터베이스

python django postgres 디비 연동

postgres 데이터베이스는 RDBMS 로 복잡한 쿼리연산, 확장성에 장점이 있고,

초기 환경설정이 다소 까다로울수 있다는 단점이 있다. 

 

윈도우환경에서 pycharm 개발툴 django 설치후

로컬 서버(지금 사용하는 내컴퓨터)에 postgres 디비서버를 설치후

database 생성했다.

 

 

아래는 django 프레임워크 소스에 postgres DB 를 연동하는 과정이다.

 

pycharm 터미널에서


pip install psycopg2


실행해서 라이브러리 설치한다.

 

설정폴더의  settings.py, urls.py 2개의 소스를 작성한다.


#settings.py

 

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/5.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-1do2#vx2!mq@l8q%@j@mymhvc872zlz1!=m7308+g0pt6ohf_o'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'database_d',         # 생성한 DB 이름
        'USER': 'users',              # PostgreSQL 사용자 이름
        'PASSWORD': '1234',           # PostgreSQL 비밀번호
        'HOST': 'localhost',          # 호스트
        'PORT': '5432',               # 포트(보통 설치시 디폴트로 5432로 생성)
        'OPTIONS': {
            'client_encoding': 'UTF8',  # 인코딩을 UTF-8로 설정
        }
    }
}

 


#urls.py

# your_project_name/urls.py (보통 config/urls.py에 위치)

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

urlpatterns = [
    path('admin/', admin.site.urls),  # 관리자 페이지 URL 추가
    # 다른 URL 패턴들...
]


그후 계정이 있어야 하는데 터미널에 


python manage.py migrate
python manage.py createsuperuser
python manage.py runserver


순서대로 한줄씩 터미널에 입력후 실행한다.

python manage.py createsuperuser

에서 사용할 아이디와 패스워드를 만들수 있다.

 

 

python manage.py runserver

실행후 브라우저에 

http://127.0.0.1:8000/admin 

을 입력시 브라우저에 아래 화면이 나오면 django 프레임워크에 postgres 데이터베이스를 연동 한것이다.