init: initial Django LMS backend

This commit is contained in:
Flook
2026-04-26 05:22:02 +07:00
commit bca709b071
40 changed files with 699 additions and 0 deletions
+23
View File
@@ -0,0 +1,23 @@
# --- Python ---
__pycache__/
*.py[cod]
*$py.class
.venv/
env/
venv/
ENV/
# --- Django ---
db.sqlite3
db.sqlite3-journal
/static/
/media/
.env
# --- IDEs ---
.vscode/
.idea/
# --- OS ---
.DS_Store
Thumbs.db
+23
View File
@@ -0,0 +1,23 @@
# --- Python ---
__pycache__/
*.py[cod]
*$py.class
.venv/
env/
venv/
ENV/
# --- Django ---
db.sqlite3
db.sqlite3-journal
/static/
/media/
.env
# --- IDEs ---
.vscode/
.idea/
# --- OS ---
.DS_Store
Thumbs.db
+53
View File
@@ -0,0 +1,53 @@
# =========================
# Base Image
# =========================
FROM python:3.12-slim
# =========================
# Environment Variables
# =========================
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
# =========================
# System Dependencies
# =========================
RUN apt-get update && apt-get install -y \
build-essential \
libpq-dev \
curl \
&& rm -rf /var/lib/apt/lists/*
# =========================
# Working Directory
# =========================
WORKDIR /app
# =========================
# Python Dependencies
# =========================
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# =========================
# Copy Project Files
# =========================
COPY . .
# =========================
# Collect Static Files
# =========================
RUN python manage.py collectstatic --noinput
# =========================
# Expose Application Port
# =========================
EXPOSE 8000
# =========================
# Run Application
# =========================
CMD ["gunicorn", "core.wsgi:application", \
"--bind", "0.0.0.0:8000", \
"--workers", "3", \
"--timeout", "120"]
View File
+78
View File
@@ -0,0 +1,78 @@
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from unfold.admin import ModelAdmin
from .models import (
CustomUser,
StudentProfile,
InstructorProfile,
AdminProfile,
)
@admin.register(CustomUser)
class CustomUserAdmin(UserAdmin, ModelAdmin):
model = CustomUser
list_display = (
"email",
"username",
"is_active",
"is_staff",
)
list_filter = (
"is_active",
"is_staff",
"is_superuser",
)
search_fields = ("email","username")
ordering = ("email",)
fieldsets = (
(None, {"fields": ("email", "username", "password")}),
("Permissions", {"fields": ("is_active", "is_staff", "is_superuser", "groups")}),
("Important Dates", {"fields": ("last_login", "date_joined")}),
)
add_fieldsets = (
(None, {
"classes": ("wide",),
"fields": (
"email",
"username",
"password1",
"password2",
"is_staff",
"is_superuser",
),
}),
)
@admin.register(StudentProfile)
class StudentProfileAdmin(ModelAdmin):
list_display = ("user", "is_active")
search_fields = ("user__email", "user__username")
list_filter = ("is_active",)
@admin.register(InstructorProfile)
class InstructorProfileAdmin(ModelAdmin):
list_display = ("user", "expertise", "is_verified", "is_active")
search_fields = ("user__email", "user__username", "expertise")
list_filter = ("is_active", "is_verified")
actions = ["verify_instructor", "unverify_instructor"]
@admin.action(description="ยืนยันผู้สอน")
def verify_instructor(self, request, queryset):
queryset.update(is_verified=True)
@admin.action(description="ยกเลิกการยืนยันผู้สอน")
def unverify_instructor(self, request, queryset):
queryset.update(is_verified=False)
@admin.register(AdminProfile)
class AdminProfileAdmin(ModelAdmin):
list_display = ("user", "is_active", "is_super")
list_filter = ("is_active", "is_super")
+5
View File
@@ -0,0 +1,5 @@
from django.apps import AppConfig
class AccountsConfig(AppConfig):
name = 'apps.accounts'
verbose_name = "ตั้งค่าบัญชีผู้ใช้งาน"
+87
View File
@@ -0,0 +1,87 @@
# Generated by Django 6.0.2 on 2026-04-22 11:34
import django.contrib.auth.models
import django.contrib.auth.validators
import django.db.models.deletion
import django.utils.timezone
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0012_alter_user_first_name_max_length'),
]
operations = [
migrations.CreateModel(
name='CustomUser',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')),
('first_name', models.CharField(blank=True, max_length=150, verbose_name='first name')),
('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')),
('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')),
('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
('email', models.EmailField(max_length=254, unique=True)),
('phone', models.CharField(blank=True, max_length=20)),
('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.group', verbose_name='groups')),
('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.permission', verbose_name='user permissions')),
],
options={
'verbose_name': 'บัญชีผู้ใช้งาน',
'verbose_name_plural': 'บัญชีผู้ใช้งาน',
},
managers=[
('objects', django.contrib.auth.models.UserManager()),
],
),
migrations.CreateModel(
name='AdminProfile',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('is_active', models.BooleanField(default=True)),
('is_super', models.BooleanField(default=False)),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
options={
'verbose_name': 'ผู้ดูแลระบบ',
'verbose_name_plural': 'ผู้ดูแลระบบ',
},
),
migrations.CreateModel(
name='InstructorProfile',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('is_active', models.BooleanField(default=True)),
('bio', models.TextField(blank=True)),
('expertise', models.CharField(blank=True, max_length=200)),
('is_verified', models.BooleanField(default=False)),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
options={
'verbose_name': 'ผู้สอน',
'verbose_name_plural': 'ผู้สอน',
},
),
migrations.CreateModel(
name='StudentProfile',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('is_active', models.BooleanField(default=True)),
('interests', models.TextField(blank=True)),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
options={
'verbose_name': 'ผู้เรียน',
'verbose_name_plural': 'ผู้เรียน',
},
),
]
+68
View File
@@ -0,0 +1,68 @@
from django.contrib.auth.models import AbstractUser
from django.db import models
class CustomUser(AbstractUser):
email = models.EmailField(unique=True)
phone = models.CharField(max_length=20, blank=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
@property
def role(self):
roles = []
if hasattr(self, 'studentprofile'):
roles.append("student")
if hasattr(self, 'instructorprofile'):
roles.append("instructor")
if hasattr(self, 'adminprofile'):
roles.append("admin")
return roles
def save(self, *args, **kwargs):
if self.email:
self.email = self.email.lower().strip()
super().save(*args, **kwargs)
class Meta:
verbose_name = "บัญชีผู้ใช้งาน"
verbose_name_plural = "บัญชีผู้ใช้งาน"
def __str__(self):
return self.email
class BaseRoleProfile(models.Model):
user = models.OneToOneField(
CustomUser,
on_delete=models.CASCADE,
)
is_active = models.BooleanField(default=True)
class Meta:
abstract = True
class StudentProfile(BaseRoleProfile):
interests = models.TextField(blank=True)
class Meta:
verbose_name = "ผู้เรียน"
verbose_name_plural = "ผู้เรียน"
class InstructorProfile(BaseRoleProfile):
bio = models.TextField(blank=True)
expertise = models.CharField(max_length=200, blank=True)
is_verified = models.BooleanField(default=False)
class Meta:
verbose_name = "ผู้สอน"
verbose_name_plural = "ผู้สอน"
def __str__(self):
return f"Instructor: {self.user.email}"
class AdminProfile(BaseRoleProfile):
is_super = models.BooleanField(default=False)
class Meta:
verbose_name = "ผู้ดูแลระบบ"
verbose_name_plural = "ผู้ดูแลระบบ"
+3
View File
@@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.
+3
View File
@@ -0,0 +1,3 @@
from django.shortcuts import render
# Create your views here.
View File
+3
View File
@@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.
+5
View File
@@ -0,0 +1,5 @@
from django.apps import AppConfig
class CommonConfig(AppConfig):
name = 'apps.common'
View File
+3
View File
@@ -0,0 +1,3 @@
from django.db import models
# Create your models here.
+3
View File
@@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.
+3
View File
@@ -0,0 +1,3 @@
from django.shortcuts import render
# Create your views here.
View File
+3
View File
@@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.
+5
View File
@@ -0,0 +1,5 @@
from django.apps import AppConfig
class ContentConfig(AppConfig):
name = 'apps.content'
View File
+3
View File
@@ -0,0 +1,3 @@
from django.db import models
# Create your models here.
+3
View File
@@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.
+3
View File
@@ -0,0 +1,3 @@
from django.shortcuts import render
# Create your views here.
View File
+3
View File
@@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.
+5
View File
@@ -0,0 +1,5 @@
from django.apps import AppConfig
class CoursesConfig(AppConfig):
name = 'apps.courses'
View File
+3
View File
@@ -0,0 +1,3 @@
from django.db import models
# Create your models here.
+3
View File
@@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.
+3
View File
@@ -0,0 +1,3 @@
from django.shortcuts import render
# Create your views here.
View File
+16
View File
@@ -0,0 +1,16 @@
"""
ASGI config for core project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/6.0/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings')
application = get_asgi_application()
+196
View File
@@ -0,0 +1,196 @@
"""
Django settings for core project.
Generated by 'django-admin startproject' using Django 6.0.2.
For more information on this file, see
https://docs.djangoproject.com/en/6.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/6.0/ref/settings/
"""
import os
from pathlib import Path
from django.templatetags.static import static
# 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/6.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-vk@6jztjz7k6hb2%x%toy0*1&##oy%v%%c$o32w*ptq)+-b0$5'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
"unfold", # ต้องอยู่บนสุด ก่อน django.contrib.admin
"unfold.contrib.filters", # Filter สวย ๆ
"unfold.contrib.forms", # ฟอร์มสวย ๆ
"unfold.contrib.import_export", # ใช้คู่กับ import_export
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# Third-party Apps
'rest_framework', # สำหรับจัดการ API
'corsheaders', # สำหรับจัดการ CORS (สำคัญมากถ้ามีหน้าบ้านแยก)
# LOCAL APPS
'apps.accounts',
'apps.content',
'apps.courses',
'apps.common',
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware', # สำคัญมากสำหรับ Frontend
'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 = 'core.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'core.wsgi.application'
# Database
# https://docs.djangoproject.com/en/6.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql', # เปลี่ยนจาก django_cockroachdb
'NAME': os.environ.get('DB_NAME', 'my_db'),
'HOST': os.environ.get('DB_HOST', 'localhost'),
'PORT': os.environ.get('DB_PORT', '5432'), # พอร์ตมาตรฐาน PostgreSQL
'USER': os.environ.get('DB_USER', 'user'),
'PASSWORD': os.environ.get('DB_PASSWORD', 'password'),
'OPTIONS': {
'connect_timeout': 5,
},
'ATOMIC_REQUESTS': True, # PostgreSQL รองรับ Atomic Requests ได้อย่างมีประสิทธิภาพ
},
}
REST_FRAMEWORK = {
"DEFAULT_AUTHENTICATION_CLASSES": (
"rest_framework.authentication.SessionAuthentication",
"rest_framework.authentication.TokenAuthentication",
),
}
CORS_ALLOW_ALL_ORIGINS = True # ควรเป็น False ใน Production
# Password validation
# https://docs.djangoproject.com/en/6.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/6.0/topics/i18n/
# เปลี่ยนเป็นภาษาไทยสำหรับหน้า Admin
LANGUAGE_CODE = 'th'
# ตั้งเป็นเวลาประเทศไทย
TIME_ZONE = 'Asia/Bangkok'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/6.0/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
AUTH_USER_MODEL = "accounts.CustomUser"
# ตั้งค่าเมนูและ Dashboard (UNFOLD Configuration)
UNFOLD = {
"SITE_TITLE": "LMS เพื่อสาธารณะ",
"SITE_HEADER": "ระบบคลังความรู้เพื่อเยาวชนไทย",
"SITE_SYMBOL": "menu_book",
"SHOW_HISTORY": True,
"STYLES": [
lambda request: static("css/unfold_th_font.css"),
],
"SCRIPTS": [
lambda request: static("unfold/js/admin.js"),
],
"COLORS": {
"primary": {
"50": "#e0f2fe", # ฟ้าอ่อนมาก (ใช้กับพื้นหลังอ่อน)
"100": "#bae6fd",
"200": "#7dd3fc",
"300": "#38bdf8",
"400": "#0ea5e9",
"500": "#0284c7", # สีหลัก
"600": "#0369a1",
"700": "#075985",
"800": "#0c4a6e",
"900": "#082f49",
"950": "#020617",
},
# ถ้าอยากปรับโทนสีเทา/พื้นหลัง (Base) ให้เข้มขรึมขึ้น
"base": {
"50": "#f8fafc",
"900": "#0f172a", # สีพื้นหลัง Dark Mode
"950": "#020617",
},
},
}
+22
View File
@@ -0,0 +1,22 @@
"""
URL configuration for core project.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/6.0/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
urlpatterns = [
path('admin/', admin.site.urls),
]
+16
View File
@@ -0,0 +1,16 @@
"""
WSGI config for core project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/6.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings')
application = get_wsgi_application()
+25
View File
@@ -0,0 +1,25 @@
version: '3.8'
services:
db:
image: postgres:16-alpine
container_name: postgres-db
restart: always
environment:
POSTGRES_DB: my_db
POSTGRES_USER: user
POSTGRES_PASSWORD: password # รหัสผ่านสำหรับช่วงพัฒนาเท่านั้น
ports:
- "5432:5432"
volumes:
- postgres_data:/var/lib/postgresql/data
# Healthcheck เพื่อให้ backend รอจนกว่า DB จะพร้อม
healthcheck:
test: ["CMD-SHELL", "pg_isready -U user -d my_db"]
interval: 5s
timeout: 5s
retries: 5
volumes:
postgres_data:
minio_data:
+22
View File
@@ -0,0 +1,22 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
+8
View File
@@ -0,0 +1,8 @@
Django==6.0.2
djangorestframework==3.17.1
django-unfold==0.90.0
djangorestframework-simplejwt==5.5.1
django-allauth==65.16.1
python-dotenv==1.2.2
psycopg[binary]==3.3.3
django-cors-headers==4.9.0