Djangoプロジェクトの環境構築とアプリケーション設計

開発環境の構築

CentOS 7ベースのLinux環境でDjangoプロジェクトを構築します。仮想環境管理にはcondaを採用し、以下の手順で設定を行います。

仮想環境の作成

python -m venv project_env
source project_env/bin/activate

必要なパッケージのインストール

Python 3.10とDjango 4.2.xを基盤に、データベース接続用ライブラリを追加します。

pip install django==4.2.11 mysqlclient

プロジェクトフレームワークの構成

基本ディレクトリ構造の作成

プロジェクトルートにアプリケーション専用ディレクトリを配置します。

django-admin startproject core
mkdir -p core/apps/{customer,product,cart,checkout}
touch core/apps/__init__.py
mv core/{customer,product,cart,checkout} core/apps/

テンプレートディレクトリの設定

mkdir -p templates/{product,customer,cart,checkout}

設定ファイルのカスタマイズ

モジュール検索パスの追加

appsディレクトリをインポートパスに含めるため、settings.pyに追加記述します。

import sys
sys.path.insert(0, BASE_DIR / 'apps')

ホスト設定の調整

ALLOWED_HOSTS = ['your_server_ip', 'localhost']

静的ファイルパスの定義

STATICFILES_DIRS = [
    BASE_DIR / 'static',
]

データモデルの実装

共通基底モデルの作成

core/db/base_models.pyに抽象モデルを定義します。

from django.db import models

class AbstractBaseModel(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        abstract = True

カスタムユーザーモデルの実装

customerアプリ内にDjango組み込み認証を拡張したモデルを作成します。

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

class Customer(AbstractUser, AbstractBaseModel):
    phone_number = models.CharField(max_length=15, blank=True)
    
    class Meta:
        db_table = 'customer_profile'

認証システムの設定

settings.pyにカスタムモデルを指定します。

AUTH_USER_MODEL = 'customer.Customer'

リッチテキストフィールドの実装

CKEditorの統合

productアプリで商品詳細説明にリッチエディタを適用します。

# requirements.txt
django-ckeditor==6.7.0

# settings.py
INSTALLED_APPS += ['ckeditor',]
CKEDITOR_CONFIGS = {
    'default': {
        'width': 750,
        'height': 300,
    }
}

# product/models.py
from ckeditor.fields import RichTextField

class Product(models.Model):
    description = RichTextField(blank=True, verbose_name="商品説明")

マイグレーションの実行

python manage.py makemigrations
python manage.py migrate

タグ: Django Python ckeditor virtualenv django-models

6月1日 20:40 投稿