Skip to content

Instantly share code, notes, and snippets.

@jinto
Last active July 1, 2025 15:21
Show Gist options
  • Select an option

  • Save jinto/77eb9ad7c811b6b1e92c1017eec2016f to your computer and use it in GitHub Desktop.

Select an option

Save jinto/77eb9ad7c811b6b1e92c1017eec2016f to your computer and use it in GitHub Desktop.
커서용 장고 생성 파일

Django 프로젝트 생성 AI 프롬프트

역할

당신은 최신 파이썬 및 웹 개발 도구에 능숙한 전문 Django 개발자입니다. 아래 명세에 따라 재사용 가능하고 확장성 높은 Django 프로젝트의 전체 구조와 코드를 생성해야 합니다. 모든 코드는 명확하고, 실용적이며, 즉시 실행 가능해야 합니다.

프로젝트 명세

1. 기본 환경 설정

  1. 가상환경 및 의존성 설치

    • uv를 사용하여 가상환경을 초기화합니다.
    • django, django-allauth, django-tailwind, psycopg2-binary, python-dotenv를 설치합니다.
    uv init --name PROJECT_NAME --python 3.12
    uv add django "django-allauth[socialaccount]" "django-tailwind[reload]" psycopg2-binary python-dotenv

    uv init 이 만든 main.py 삭제

    rm main.py
  2. 프로젝트 생성

    • 현재 디렉토리에 config라는 이름의 Django 프로젝트를 생성합니다.
    uv run django-admin startproject config .

2. 설정 파일 구조화 및 분리

  1. 디렉토리 구조 변경

    • config/settings 디렉토리를 만들고, 기존 settings.pybase.py로 이름을 바꿔 이동시킵니다.
    • settings 디렉토리를 파이썬 패키지로 만들기 위해 __init__.py 파일을 생성합니다.
    mkdir config/settings
    mv config/settings.py config/settings/base.py
    touch config/settings/__init__.py
  2. 환경 변수 관리 (.env 파일)

    • 프로젝트 루트에 .env 파일을 생성하고 아래 내용을 추가합니다. SECRET_KEY는 Django가 생성한 base.py(이전 settings.py)에서 복사해옵니다. (touch .env 로 생성을 먼저해야한다.)

    .env

    ENV_NAME='local'
    DJANGO_SECRET_KEY='여기에_생성된_시크릿_키를_붙여넣으세요'
    DATABASE_URL='postgres://user:password@localhost:5432/dbname' # 예시
    
  3. 기본 설정 (config/settings/base.py)

    • base.py 파일을 아래 내용으로 완전히 수정합니다. python-dotenv를 사용하여 .env 파일의 변수를 로드합니다. BASE_DIR 경로도 수정합니다.

    config/settings/base.py

    import os
    from pathlib import Path
    from dotenv import load_dotenv
    
    # Build paths inside the project like this: BASE_DIR / 'subdir'.
    BASE_DIR = Path(__file__).resolve().parent.parent.parent
    
    # Load .env file
    load_dotenv(BASE_DIR / '.env')
    
    # Quick-start development settings - unsuitable for production
    # See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/
    
    # SECURITY WARNING: keep the secret key used in production secret!
    SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY')
    
    # Application definition
    INSTALLED_APPS = [
        "django.contrib.admin",
        "django.contrib.auth",
        "django.contrib.contenttypes",
        "django.contrib.sessions",
        "django.contrib.messages",
        "django.contrib.staticfiles",
        'django.contrib.sites',
    
        # 3rd party
        'allauth',
        'allauth.account',
        'allauth.socialaccount',
        'tailwind',
        # 'theme',  # Tailwind init 후에 추가됩니다
    
        # local apps
        # 'member',  # 앱 생성 후에 추가됩니다
        # '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",
        "allauth.account.middleware.AccountMiddleware", # allauth middleware
    ]
    
    ROOT_URLCONF = "config.urls"
    
    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",
                ],
            },
        },
    ]
    
    WSGI_APPLICATION = "config.wsgi.application"
    
    # Database
    # https://docs.djangoproject.com/en/5.0/ref/settings/#databases
    # 개발 환경에서는 sqlite를, 운영 환경에서는 다른 DB를 사용할 수 있도록 local.py/prod.py에서 재정의합니다.
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': BASE_DIR / 'db.sqlite3',
        }
    }
    
    
    # Password validation
    # https://docs.djangoproject.com/en/5.0/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/5.0/topics/i18n/
    LANGUAGE_CODE = "ko-kr"
    TIME_ZONE = "Asia/Seoul"
    USE_I18N = True
    USE_TZ = True
    
    # Static files (CSS, JavaScript, Images)
    # https://docs.djangoproject.com/en/5.0/howto/static-files/
    STATIC_URL = "static/"
    STATICFILES_DIRS = [
        # BASE_DIR / "theme" / "static",  # Tailwind init 후에 활성화됩니다
    ]
    
    # Default primary key field type
    # https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field
    DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
    
    # Custom User Model
    # AUTH_USER_MODEL = 'member.User'  # member 앱 생성 후에 활성화됩니다
    
    # django-allauth
    AUTHENTICATION_BACKENDS = (
        'django.contrib.auth.backends.ModelBackend',
        'allauth.account.auth_backends.AuthenticationBackend',
    )
    SITE_ID = 1
    ACCOUNT_EMAIL_VERIFICATION = 'none' # 개발 편의를 위해 'none'으로 설정
    LOGIN_REDIRECT_URL = '/'
    LOGOUT_REDIRECT_URL = '/'
    
    # django-tailwind
    TAILWIND_APP_NAME = 'theme'
    INTERNAL_IPS = [
        "127.0.0.1",
    ]
  4. 환경별 설정 파일 생성

    • local.pyprod.py 파일을 생성합니다.

    config/settings/local.py

    from .base import *
    
    DEBUG = True
    ALLOWED_HOSTS = []

    config/settings/prod.py

    from .base import *
    import dj_database_url
    
    DEBUG = False
    ALLOWED_HOSTS = ['*'] # 실제 프로덕션 환경에서는 도메인을 명시해야 합니다.
    
    # .env 파일에서 DATABASE_URL을 읽어와 DB 설정
    DATABASES['default'] = dj_database_url.config(conn_max_age=600)
  5. 엔트리포인트 수정

    • manage.py, config/asgi.py, config/wsgi.py 파일이 ENV_NAME 환경 변수를 읽어 적절한 설정 파일을 로드하도록 수정합니다. 각 파일에서 os.environ.setdefault 부분을 아래와 같이 수정하세요. import os는 각 파일 상단에 이미 존재합니다.
    # 기존 코드: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")
    # 수정 코드:
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", f"config.settings.{os.environ.get('ENV_NAME', 'local')}")

3. 앱 및 기본 뷰 생성

  1. 앱 생성

    • main 앱과 member 앱을 생성하고, 최상위 templates 디렉토리를 만듭니다.
    uv run python manage.py startapp main
    uv run python manage.py startapp member
    mkdir templates
  2. settings/base.py에 앱 추가

    • 앱 생성 후 config/settings/base.pyINSTALLED_APPS에 주석 처리된 앱들을 활성화합니다:
    # local apps
    'member',
    'main',
    • AUTH_USER_MODEL 설정도 활성화합니다:
    AUTH_USER_MODEL = 'member.User'
  3. 기본 템플릿 구조 생성

    • templates 디렉토리 안에 base.htmlindex.html을 생성합니다.

    templates/base.html

    {% load static tailwind_tags %}
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>{% block title %}Django Project{% endblock %}</title>
        {% tailwind_css %}
    </head>
    <body class="bg-gray-100">
        <div class="container mx-auto mt-8">
            {% block content %}{% endblock %}
        </div>
    </body>
    </html>

    templates/index.html

    {% extends "base.html" %}
    
    {% block title %}Welcome!{% endblock %}
    
    {% block content %}
    <div class="bg-white p-6 rounded-lg shadow-lg text-center">
        <h1 class="text-4xl font-bold text-blue-600 mb-4">Hello, Django with Tailwind CSS!</h1>
        <p class="text-gray-700">This is a sample index page.</p>
    </div>
    {% endblock %}
  4. URL 및 뷰 연결

    • main 앱에 urls.py를 생성하고 views.py를 수정합니다.
    • config/urls.pymain 앱의 URL을 포함시킵니다.

    main/views.py

    from django.shortcuts import render
    
    def index(request):
        return render(request, 'index.html')

    main/urls.py

    from django.urls import path
    from . import views
    
    app_name = 'main'
    
    urlpatterns = [
        path('', views.index, name='index'),
    ]

    config/urls.py

    from django.contrib import admin
    from django.urls import path, include
    
    urlpatterns = [
        path("admin/", admin.site.urls),
        path('accounts/', include('allauth.urls')),
        path("", include("main.urls", namespace="main")),
    ]

4. 사용자 모델 커스터마이징

  • member 앱에서 AbstractUser를 상속받는 커스텀 User 모델을 생성합니다.

member/models.py

from django.contrib.auth.models import AbstractUser
from django.db import models

class User(AbstractUser):
    # 여기에 필요한 추가 필드를 정의할 수 있습니다.
    # 예: nickname = models.CharField(max_length=50, blank=True)
    pass

member/admin.py

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import User

@admin.register(User)
class CustomUserAdmin(UserAdmin):
    # 어드민 페이지에 표시할 필드를 설정할 수 있습니다.
    pass

5. Tailwind CSS 설정

  1. Tailwind 초기화

    • theme라는 이름의 앱으로 tailwind를 초기화합니다.
    uv run python manage.py tailwind init --app-name theme --no-input
  2. settings/base.py에 theme 앱 추가

    • Tailwind 초기화 후 config/settings/base.pyINSTALLED_APPS에 theme 앱을 활성화합니다:
    # 3rd party
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'tailwind',
    'theme',  # 주석 해제
    • STATICFILES_DIRS도 활성화합니다:
    STATICFILES_DIRS = [
        BASE_DIR / "theme" / "static",
    ]
  3. Tailwind 설정 파일 수정

    • theme/static_src/tailwind.config.js 파일의 content 부분을 수정하여 templates 디렉토리의 HTML 파일들을 스캔하도록 합니다.

    theme/static_src/tailwind.config.js

    /** @type {import('tailwindcss').Config} */
    module.exports = {
        content: [
            '../../templates/**/*.html',
            '../../**/templates/**/*.html',
        ],
        theme: {
            extend: {},
        },
        plugins: [
            require('@tailwindcss/forms'),
            require('@tailwindcss/typography'),
        ],
    }
  4. Tailwind CSS 설치

    • Tailwind 종속성을 설치합니다.
    uv run python manage.py tailwind install

6. 개발 도구 설정

  1. .gitignore 생성

    • 프로젝트 루트에 .gitignore 파일을 생성합니다.

    .gitignore

    # Environments
    .env
    .venv/
    env/
    venv/
    
    # Django
    *.log
    *.pot
    *.pyc
    __pycache__/
    db.sqlite3
    
    # Static files
    /theme/static/css/
    
    # IDE
    .idea/
    .vscode/
    
  2. 개발 의존성 및 포매터 설정

    • black, ruff, lefthook, pytest, pytest-django를 개발 의존성으로 추가합니다.
    uv add --dev black ruff lefthook pytest pytest-django
  3. pyproject.toml 설정

    • ruffblack 설정을 추가합니다.

    pyproject.toml

    [tool.black]
    line-length = 88
    
    [tool.ruff]
    line-length = 88
    select = ["E", "W", "F", "I", "C", "B"]
    ignore = ["E501"]
  4. lefthook.yml 설정

    • Git commit/push 전에 코드를 검사하도록 lefthook을 설정합니다.

    lefthook.yml

    pre-commit:
      commands:
        check-format:
          run: uv run black . --check && uv run ruff check .
        test:
          run: uv run pytest
    
    pre-push:
      commands:
        check-format:
          run: uv run black . --check && uv run ruff check .
        test:
          run: uv run pytest
    • lefthook을 git hooks에 설치합니다.
    lefthook install

7. 초기 마이그레이션 및 관리자 생성

  1. 마이그레이션 파일 생성 및 적용

    uv run python manage.py makemigrations
    uv run python manage.py migrate
  2. 슈퍼유저 생성

    uv run python manage.py createsuperuser

8. README.md 생성

  • 프로젝트의 구조와 실행 방법을 설명하는 README.md 파일을 생성합니다.

README.md

# My Django Project

이 프로젝트는 Django, Tailwind CSS, Allauth를 사용하여 구성되었습니다.

## ⚙️ 초기 설정

1.  **가상환경 활성화 및 의존성 설치**:
    ```bash
    uv sync
    ```

2.  **환경 변수 설정**:
    - `.env.example` 파일을 복사하여 `.env` 파일을 생성하고, 내부 변수들을 자신의 환경에 맞게 수정합니다.
    ```bash
    cp .env.example .env
    ```

3.  **데이터베이스 마이그레이션**:
    ```bash
    uv run python manage.py migrate
    ```

4.  **관리자 계정 생성**:
    ```bash
    uv run python manage.py createsuperuser
    ```

## 🚀 개발 서버 실행

1.  **Tailwind 빌드 감시**: (새 터미널에서 실행)
    - CSS 변경 사항을 실시간으로 감지하고 빌드합니다.
    ```bash
    uv run python manage.py tailwind start
    ```

2.  **Django 개발 서버 실행**: (다른 새 터미널에서 실행)
    ```bash
    uv run python manage.py runserver
    ```

## ✅ 테스트 및 코드 품질

- **테스트 실행**:
  ```bash
  uv run pytest
  • Lefthook 테스트:

    • lefthook이 올바르게 설정되었는지 확인하려면, run 명령어를 사용할 수 있습니다.
    # pre-commit 훅 실행 테스트
    lefthook run pre-commit
  • 코드 포매팅:

    uv run black .
    uv run ruff check . --fix
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment