Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions octofit-tracker/backend/manage.py
Original file line number Diff line number Diff line change
@@ -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", "octofit_tracker.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()
Empty file.
8 changes: 8 additions & 0 deletions octofit-tracker/backend/octofit_tracker/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from django.contrib import admin
from .models import User, Team, Activity, Leaderboard, Workout

admin.site.register(User)
admin.site.register(Team)
admin.site.register(Activity)
admin.site.register(Leaderboard)
admin.site.register(Workout)
16 changes: 16 additions & 0 deletions octofit-tracker/backend/octofit_tracker/asgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
ASGI config for octofit_tracker 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/4.1/howto/deployment/asgi/
"""

import os

from django.core.asgi import get_asgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "octofit_tracker.settings")

application = get_asgi_application()
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import logging
import sys
import os
from django.core.management.base import BaseCommand
from octofit_tracker.models import User, Team, Activity, Leaderboard, Workout
from bson import ObjectId
from datetime import timedelta

# Add the backend directory to the Python path
sys.path.append(os.path.join(os.path.dirname(__file__), '../../../'))

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

class Command(BaseCommand):
help = 'Populate the octofit_db database with test data'

def handle(self, *args, **kwargs):
# Clear existing data
User.objects.all().delete()
Team.objects.all().delete()
Activity.objects.all().delete()
Leaderboard.objects.all().delete()
Workout.objects.all().delete()

# Create users
users = [
User(_id=ObjectId(), username='thundergod', email='thundergod@mhigh.edu', password='password123'),
User(_id=ObjectId(), username='metalgeek', email='metalgeek@mhigh.edu', password='password123'),
User(_id=ObjectId(), username='zerocool', email='zerocool@mhigh.edu', password='password123'),
User(_id=ObjectId(), username='crashoverride', email='crashoverride@mhigh.edu', password='password123'),
User(_id=ObjectId(), username='sleeptoken', email='sleeptoken@mhigh.edu', password='password123'),
]
for user in users:
user.save()

# Log user creation
for user in users:
logger.debug(f"Created user: {user.username}, {user.email}")

# Create teams
team1 = Team(_id=ObjectId(), name='Blue Team')
team2 = Team(_id=ObjectId(), name='Gold Team')
team1.save()
team2.save()
team1.members.add(users[0], users[1])
team2.members.add(users[2], users[3], users[4])

# Log team creation
logger.debug(f"Created team: {team1.name} with members {[member.username for member in team1.members.all()]}")
logger.debug(f"Created team: {team2.name} with members {[member.username for member in team2.members.all()]}")

# Create activities
activities = [
Activity(_id=ObjectId(), user=users[0], activity_type='Cycling', duration=timedelta(hours=1)),
Activity(_id=ObjectId(), user=users[1], activity_type='Crossfit', duration=timedelta(hours=2)),
Activity(_id=ObjectId(), user=users[2], activity_type='Running', duration=timedelta(hours=1, minutes=30)),
Activity(_id=ObjectId(), user=users[3], activity_type='Strength', duration=timedelta(minutes=30)),
Activity(_id=ObjectId(), user=users[4], activity_type='Swimming', duration=timedelta(hours=1, minutes=15)),
]
Activity.objects.bulk_create(activities)

# Log activity creation
for activity in activities:
logger.debug(f"Created activity: {activity.activity_type} for user {activity.user.username}")

# Create leaderboard entries
leaderboard_entries = [
Leaderboard(_id=ObjectId(), user=users[0], score=100),
Leaderboard(_id=ObjectId(), user=users[1], score=90),
Leaderboard(_id=ObjectId(), user=users[2], score=95),
Leaderboard(_id=ObjectId(), user=users[3], score=85),
Leaderboard(_id=ObjectId(), user=users[4], score=80),
]
Leaderboard.objects.bulk_create(leaderboard_entries)

# Log leaderboard creation
for entry in leaderboard_entries:
logger.debug(f"Created leaderboard entry: {entry.user.username} with score {entry.score}")

# Create workouts
workouts = [
Workout(_id=ObjectId(), name='Cycling Training', description='Training for a road cycling event'),
Workout(_id=ObjectId(), name='Crossfit', description='Training for a crossfit competition'),
Workout(_id=ObjectId(), name='Running Training', description='Training for a marathon'),
Workout(_id=ObjectId(), name='Strength Training', description='Training for strength'),
Workout(_id=ObjectId(), name='Swimming Training', description='Training for a swimming competition'),
]
Workout.objects.bulk_create(workouts)

# Log workout creation
for workout in workouts:
logger.debug(f"Created workout: {workout.name}, {workout.description}")

self.stdout.write(self.style.SUCCESS('Successfully populated the database with test data.'))
28 changes: 28 additions & 0 deletions octofit-tracker/backend/octofit_tracker/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
from djongo import models

class User(models.Model):
_id = models.ObjectIdField()
username = models.CharField(max_length=100)
email = models.EmailField(unique=True)
password = models.CharField(max_length=100)

class Team(models.Model):
_id = models.ObjectIdField()
name = models.CharField(max_length=100)
members = models.ArrayReferenceField(to=User, on_delete=models.CASCADE)

class Activity(models.Model):
_id = models.ObjectIdField()
user = models.ForeignKey(User, on_delete=models.CASCADE)
activity_type = models.CharField(max_length=100)
duration = models.DurationField()

class Leaderboard(models.Model):
_id = models.ObjectIdField()
user = models.ForeignKey(User, on_delete=models.CASCADE)
score = models.IntegerField()

class Workout(models.Model):
_id = models.ObjectIdField()
name = models.CharField(max_length=100)
description = models.TextField()
48 changes: 48 additions & 0 deletions octofit-tracker/backend/octofit_tracker/serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
from rest_framework import serializers
from .models import User, Team, Activity, Leaderboard, Workout
from bson import ObjectId

class ObjectIdField(serializers.Field):
def to_representation(self, value):
return str(value)

def to_internal_value(self, data):
return ObjectId(data)

class UserSerializer(serializers.ModelSerializer):
_id = ObjectIdField()

class Meta:
model = User
fields = '__all__'

class TeamSerializer(serializers.ModelSerializer):
_id = ObjectIdField()
members = UserSerializer(many=True)

class Meta:
model = Team
fields = '__all__'

class ActivitySerializer(serializers.ModelSerializer):
_id = ObjectIdField()
user = ObjectIdField()

class Meta:
model = Activity
fields = '__all__'

class LeaderboardSerializer(serializers.ModelSerializer):
_id = ObjectIdField()
user = UserSerializer() # Expand the user object

class Meta:
model = Leaderboard
fields = '__all__'

class WorkoutSerializer(serializers.ModelSerializer):
_id = ObjectIdField()

class Meta:
model = Workout
fields = '__all__'
147 changes: 147 additions & 0 deletions octofit-tracker/backend/octofit_tracker/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
"""
Django settings for octofit_tracker project.

Generated by 'django-admin startproject' using Django 4.1.

For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""

from pathlib import Path

# 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/4.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "django-insecure-+)!))a2x3l=vlw)$6$*@dg0c*c@c0g#wmko#@@+p7(#qvtrxqx"

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['symmetrical-space-goggles-r4jxqxx67wrhppg-8000.app.github.dev', 'localhost', '127.0.0.1']


# Application definition

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'djongo',
'corsheaders',
'octofit_tracker',
]

INSTALLED_APPS += ['corsheaders']

MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'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',
'corsheaders.middleware.CorsMiddleware',
]

ROOT_URLCONF = "octofit_tracker.urls"

TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [],
"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 = "octofit_tracker.wsgi.application"


# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases

DATABASES = {
'default': {
'ENGINE': 'djongo',
'NAME': 'octofit_db',
'HOST': 'localhost',
'PORT': 27017,
}
}

CORS_ALLOW_ALL_ORIGINS = True
CORS_ALLOW_METHODS = [
'GET',
'POST',
'PUT',
'PATCH',
'DELETE',
'OPTIONS',
]
CORS_ALLOW_HEADERS = [
'content-type',
'authorization',
'x-csrftoken',
]

# Password validation
# https://docs.djangoproject.com/en/4.1/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/4.1/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/4.1/howto/static-files/

STATIC_URL = "static/"

# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
Loading