[TIL] Django 초기 세팅하기

히끼·2024년 4월 11일

TIL

목록 보기
42/43

뒤에 나오는 내용보다 초기 세팅 과정을 잘 까먹고 찾아보게 될 것 같아 남김

프로젝트 생성 및 개발서버 실행

  1. 프로젝트 생성하기
    django-admin startproject <프로젝트 이름> <생성 디렉토리>
  2. 해당 폴더 안쪽으로 이동하기
    cd <프로젝트 폴더>
  3. 개발 서버 실행하기
    python3 manage.py runserver

앱 생성

  1. 앱 생성하기
    python3 manage.py startapp <앱 이름>
  2. 앱 등록하기 : settings.pyINSTALLED_APPS 부분에 "앱 이름", 추가

Django Template 뼈대 만들기

  1. Template 기본 경로 설정 : setting.py 내에 설정 변경

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [BASE_DIR / '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',
                ],
            },
        },
    ]
  2. 프로젝트의 최상단 경로에 templates 디렉토리 생성 후 base.html 파일 생성

    <!DOCTYPE html>
    <html lang="en">
    
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
      </head>
    
      <body>
        {% block content %}{% endblock content %}
      </body>
    
    </html>

Django MTV Pattern (디자인 패턴)

  1. URL : urls.py

    from django.contrib import admin
    from django.urls import path
    from articles import views
    
    urlpatterns = [
        path("admin/", admin.site.urls),
        path("index/", views.index),
    ]
  2. View : views.py

    from django.http import HttpResponse
    
    def index(request):
        return render(request, "index.html")
  3. Template (templates 폴더 내에 생성)

    {% extends 'base.html' %}
    
    {% block content %}
      <h1>Hello, Django!</h1>
    {% endblock content %}

0개의 댓글