django framework to run in docker w standalone mysql instance

This commit is contained in:
Cutty 2026-03-18 19:49:04 -06:00
parent 7dd5e7be4a
commit 964c10f417
18 changed files with 570 additions and 0 deletions

18
Dockerfile Normal file
View file

@ -0,0 +1,18 @@
FROM python:3.9-slim
# Install system dependencies for mysqlclient
RUN apt-get update && apt-get install -y \
pkg-config \
default-libmysqlclient-dev \
build-essential \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY requirements.txt /app/
RUN pip install --no-cache-dir -r requirements.txt
COPY . /app/
# We'll run the server via docker-compose command, but this is a default
CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]

42
docker-compose.yml Normal file
View file

@ -0,0 +1,42 @@
version: '3.8'
services:
db:
image: mysql:8.0
container_name: workouts_db
restart: always
environment:
MYSQL_DATABASE: workouts
MYSQL_ROOT_PASSWORD: rootpassword
MYSQL_USER: user
MYSQL_PASSWORD: userpassword
volumes:
- db_data:/var/lib/mysql
networks:
- workout_net
web:
build: .
container_name: workouts_web
command: >
sh -c "python manage.py migrate &&
python manage.py runserver 0.0.0.0:8000"
volumes:
- .:/app
ports:
- "8000:8000"
depends_on:
- db
environment:
- DB_NAME=workouts
- DB_USER=user
- DB_PASSWORD=userpassword
- DB_HOST=db
networks:
- workout_net
volumes:
db_data:
networks:
workout_net:

2
requirements.txt Normal file
View file

@ -0,0 +1,2 @@
Django>=4.2
mysqlclient>=2.2.0

22
zed_workouts/manage.py Normal file
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', 'zed_workouts.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()

View file

View file

@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.

View file

@ -0,0 +1,5 @@
from django.apps import AppConfig
class TrackerConfig(AppConfig):
name = 'tracker'

View file

@ -0,0 +1,45 @@
from django.db import models
class Exercise(models.Model):
GROUP_CHOICES = [
('Primary', 'Primary'),
('Secondary', 'Secondary'),
('Core', 'Core'),
]
exercise = models.CharField(max_length=255, unique=True)
type = models.CharField(max_length=100) # e.g., Chest, Back, Arms
group = models.CharField(max_length=20, choices=GROUP_CHOICES)
def __str__(self):
return f"{self.exercise} ({self.group})"
class BaseWorkoutData(models.Model):
"""Abstract base to ensure identical columns for templates and history."""
date = models.DateField(auto_now_add=True)
group = models.CharField(max_length=20)
type = models.CharField(max_length=100)
exercise = models.CharField(max_length=255)
set = models.IntegerField()
weight = models.DecimalField(max_digits=6, decimal_places=2, default=0.0)
reps = models.IntegerField(default=0)
notes = models.TextField(blank=True, null=True)
class Meta:
abstract = True
class Workout(BaseWorkoutData):
class Meta:
db_table = 'workouts'
class ChestTemplate(BaseWorkoutData):
class Meta:
db_table = 'chest'
class BackTemplate(BaseWorkoutData):
class Meta:
db_table = 'back'
class LegsTemplate(BaseWorkoutData):
class Meta:
db_table = 'legs'

View file

@ -0,0 +1,188 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Zed Workouts</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
.table-input { width: 100%; border: none; background: transparent; }
.hidden-inputs { display: none; }
</style>
</head>
<body class="bg-light p-4">
<div class="container bg-white p-4 rounded shadow">
<h2 class="mb-4">Workout Tracker</h2>
<!-- SECTION 1: Template Selection -->
<div class="row mb-3">
<div class="col-md-4">
<label class="form-label"><strong>Template</strong></label>
<select id="templateSelect" class="form-select" onchange="filterExercises()">
<option value="">Select...</option>
<option value="Chest">Chest</option>
<option value="Back">Back</option>
<option value="Legs">Legs</option>
</select>
</div>
</div>
<!-- SECTION 2: Exercise Selection -->
<div class="row mb-3">
<div class="col-md-4">
<label>Primary Group</label>
<select id="primarySelect" class="form-select"></select>
</div>
<div class="col-md-4">
<label>Secondary Group</label>
<select id="secondarySelect" class="form-select"></select>
</div>
<div class="col-md-4">
<label>Core Group</label>
<select id="coreSelect" class="form-select"></select>
</div>
</div>
<button class="btn btn-primary mb-4" onclick="generateTable()">Generate Table</button>
<!-- SECTION 3: Active Supersets Table -->
<h4>Current Block (4 Sets)</h4>
<table class="table table-bordered">
<thead class="table-dark">
<tr>
<th>Exercise</th>
<th>Group</th>
<th>Set</th>
<th>Reps</th>
<th>Weight</th>
<th>Notes</th>
</tr>
</thead>
<tbody id="activeTableBody"></tbody>
</table>
<button class="btn btn-warning mb-4" onclick="saveBlock()">Save Block (Clear Table)</button>
<!-- SECTION 4: Final Submission -->
<form method="POST">
{% csrf_token %}
<input type="hidden" name="template_name" id="formTemplateName">
<h4>Completed Workout Log</h4>
<table class="table table-striped">
<thead>
<tr><th>Exercise</th><th>Set</th><th>Reps</th><th>Weight</th><th>Notes</th></tr>
</thead>
<tbody id="logTableBody"></tbody>
</table>
<!-- Hidden inputs container for POST data -->
<div id="hiddenInputs" class="hidden-inputs"></div>
<button type="submit" class="btn btn-success btn-lg w-100 mt-3">End Workout (Submit)</button>
</form>
</div>
<script>
const exercises = {{ exercises_json|safe }};
function filterExercises() {
const template = document.getElementById('templateSelect').value;
document.getElementById('formTemplateName').value = template;
// Simple mapping logic: Chest Template implies Chest exercises for Primary, etc.
// You can customize this logic as needed.
let primaryType = [], secondaryType = [];
if (template === 'Chest') { primaryType = ['Chest']; secondaryType = ['Arms', 'Triceps']; }
else if (template === 'Back') { primaryType = ['Back']; secondaryType = ['Arms', 'Biceps']; }
else if (template === 'Legs') { primaryType = ['Legs']; secondaryType = ['Shoulders', 'Calves']; }
populateDropdown('primarySelect', 'Primary', primaryType);
populateDropdown('secondarySelect', 'Secondary', secondaryType);
populateDropdown('coreSelect', 'Core', ['Abs', 'Core']);
}
function populateDropdown(id, group, types) {
const select = document.getElementById(id);
select.innerHTML = '<option value="">Select...</option>';
exercises.forEach(ex => {
if (ex.group === group && (types.length === 0 || types.includes(ex.type))) {
const opt = document.createElement('option');
opt.value = ex.exercise;
opt.text = ex.exercise;
opt.dataset.type = ex.type;
select.appendChild(opt);
}
});
}
function generateTable() {
const tbody = document.getElementById('activeTableBody');
tbody.innerHTML = '';
const selects = [
{ el: document.getElementById('primarySelect'), group: 'Primary' },
{ el: document.getElementById('secondarySelect'), group: 'Secondary' },
{ el: document.getElementById('coreSelect'), group: 'Core' }
];
// Validate selection
if (selects.some(s => !s.el.value)) { alert("Please select all 3 exercises."); return; }
for (let set = 1; set <= 4; set++) {
selects.forEach(s => {
const opt = s.el.options[s.el.selectedIndex];
const row = `
<tr>
<td>${s.el.value}<input type="hidden" class="d-ex" value="${s.el.value}"></td>
<td>${s.group}<input type="hidden" class="d-gr" value="${s.group}">
<input type="hidden" class="d-ty" value="${opt.dataset.type}"></td>
<td>${set}<input type="hidden" class="d-st" value="${set}"></td>
<td><input type="number" class="table-input d-rp" value="0"></td>
<td><input type="number" class="table-input d-wt" step="0.5" value="0"></td>
<td><input type="text" class="table-input d-nt" placeholder="Notes"></td>
</tr>`;
tbody.insertAdjacentHTML('beforeend', row);
});
}
}
function saveBlock() {
const activeBody = document.getElementById('activeTableBody');
const logBody = document.getElementById('logTableBody');
const hiddenDiv = document.getElementById('hiddenInputs');
// Move rows from active table to log and create hidden inputs
activeBody.querySelectorAll('tr').forEach(row => {
const ex = row.querySelector('.d-ex').value;
const gr = row.querySelector('.d-gr').value;
const ty = row.querySelector('.d-ty').value;
const st = row.querySelector('.d-st').value;
const rp = row.querySelector('.d-rp').value;
const wt = row.querySelector('.d-wt').value;
const nt = row.querySelector('.d-nt').value;
// Visual Log
const logRow = `<tr><td>${ex}</td><td>${st}</td><td>${rp}</td><td>${wt}</td><td>${nt}</td></tr>`;
logBody.insertAdjacentHTML('beforeend', logRow);
// Hidden Inputs for POST
const inputs = `
<input type="hidden" name="exercise[]" value="${ex}">
<input type="hidden" name="group[]" value="${gr}">
<input type="hidden" name="type[]" value="${ty}">
<input type="hidden" name="set[]" value="${st}">
<input type="hidden" name="reps[]" value="${rp}">
<input type="hidden" name="weight[]" value="${wt}">
<input type="hidden" name="notes[]" value="${nt}">
`;
hiddenDiv.insertAdjacentHTML('beforeend', inputs);
});
// Clear Active Table
activeBody.innerHTML = '';
}
</script>
</body>
</html>

View file

@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

View file

@ -0,0 +1,6 @@
from django.urls import path
from . import views
urlpatterns = [
path('', views.workout_tracker, name='workout_tracker'),
]

View file

@ -0,0 +1,53 @@
from django.shortcuts import render, redirect
from django.db import transaction
from .models import Exercise, Workout, ChestTemplate, BackTemplate, LegsTemplate
import json
from datetime import date
def workout_tracker(request):
template_models = {
'Chest': ChestTemplate,
'Back': BackTemplate,
'Legs': LegsTemplate,
}
if request.method == 'POST':
# Data comes in as lists from the form
selected_template = request.POST.get('template_name')
exercises = request.POST.getlist('exercise[]')
groups = request.POST.getlist('group[]')
types = request.POST.getlist('type[]')
sets = request.POST.getlist('set[]')
weights = request.POST.getlist('weight[]')
reps = request.POST.getlist('reps[]')
notes = request.POST.getlist('notes[]')
TemplateModel = template_models.get(selected_template)
if TemplateModel and exercises:
with transaction.atomic():
# 1. Clear the specific Template table to replace with new data
TemplateModel.objects.all().delete()
# 2. Iterate and save to both Workouts (History) and Template (Current)
for i in range(len(exercises)):
row_data = {
'group': groups[i],
'type': types[i],
'exercise': exercises[i],
'set': int(sets[i]),
'weight': float(weights[i] or 0),
'reps': int(reps[i] or 0),
'notes': notes[i]
}
# Save to history
Workout.objects.create(**row_data)
# Save to template (date will auto-set to today)
TemplateModel.objects.create(**row_data)
return redirect('workout_tracker')
# GET: Fetch exercises for dropdowns
exercises = list(Exercise.objects.values('exercise', 'type', 'group'))
return render(request, 'tracker/index.html', {'exercises_json': json.dumps(exercises)})

View file

View file

@ -0,0 +1,16 @@
"""
ASGI config for zed_workouts 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', 'zed_workouts.settings')
application = get_asgi_application()

View file

@ -0,0 +1,128 @@
"""
Django settings for zed_workouts project.
Generated by 'django-admin startproject' using Django 6.0.3.
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/
"""
from pathlib import Path
import os
# 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-a%mr&&f^u06y=$!cylb-wv&w3^booxo*48hymemf$ldj=$vkb%'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'tracker',
]
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',
]
ROOT_URLCONF = 'zed_workouts.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 = 'zed_workouts.wsgi.application'
# Database
# https://docs.djangoproject.com/en/6.0/ref/settings/#databases
# DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': BASE_DIR / 'db.sqlite3',
# }
#}
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': os.environ.get('DB_NAME', 'workouts'),
'USER': os.environ.get('DB_USER', 'user'),
'PASSWORD': os.environ.get('DB_PASSWORD', 'userpassword'),
'HOST': os.environ.get('DB_HOST', 'db'),
'PORT': '3306',
}
}
# 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/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/6.0/howto/static-files/
STATIC_URL = 'static/'

View file

@ -0,0 +1,23 @@
"""
URL configuration for zed_workouts 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, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('tracker.urls')),
]

View file

@ -0,0 +1,16 @@
"""
WSGI config for zed_workouts 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', 'zed_workouts.settings')
application = get_wsgi_application()