commit a76455d5ad9d577bf6b96f9106671e0f836f64ba Author: TDLaouer Date: Sun Jul 13 18:11:10 2025 +0200 first commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1cf0110 --- /dev/null +++ b/.gitignore @@ -0,0 +1,138 @@ +# Django # +*.log +*.pot +*.pyc +__pycache__ +db.sqlite3 +media + +# Backup files # +*.bak + +# If you are using PyCharm # +# User-specific stuff +.idea/**/workspace.xml +.idea/**/tasks.xml +.idea/**/usage.statistics.xml +.idea/**/dictionaries +.idea/**/shelf + +# AWS User-specific +.idea/**/aws.xml + +# Generated files +.idea/**/contentModel.xml + +# Sensitive or high-churn files +.idea/**/dataSources/ +.idea/**/dataSources.ids +.idea/**/dataSources.local.xml +.idea/**/sqlDataSources.xml +.idea/**/dynamic.xml +.idea/**/uiDesigner.xml +.idea/**/dbnavigator.xml + +# Gradle +.idea/**/gradle.xml +.idea/**/libraries + +# File-based project format +*.iws + +# IntelliJ +out/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Python # +*.py[cod] +*$py.class + +# Distribution / packaging +.Python build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.whl +*.egg-info/ +.installed.cfg +*.egg +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +.pytest_cache/ +nosetests.xml +coverage.xml +*.cover +.hypothesis/ + +# Jupyter Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery +celerybeat-schedule.* + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ + +# Sublime Text # +*.tmlanguage.cache +*.tmPreferences.cache +*.stTheme.cache +*.sublime-workspace +*.sublime-project + +# sftp configuration file +sftp-config.json + +# Package control specific files Package +Control.last-run +Control.ca-list +Control.ca-bundle +Control.system-ca-bundle +GitHub.sublime-settings + +# Visual Studio Code # +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +.history \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..a88f8b7 --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +# Smash or Pass with Django Rest Framework diff --git a/api/__init__.py b/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/api/admin.py b/api/admin.py new file mode 100644 index 0000000..8c38f3f --- /dev/null +++ b/api/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/api/apps.py b/api/apps.py new file mode 100644 index 0000000..66656fd --- /dev/null +++ b/api/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class ApiConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'api' diff --git a/api/migrations/0001_initial.py b/api/migrations/0001_initial.py new file mode 100644 index 0000000..6d3f05f --- /dev/null +++ b/api/migrations/0001_initial.py @@ -0,0 +1,34 @@ +# Generated by Django 5.2.4 on 2025-07-12 12:37 + +import django.db.models.deletion +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + ] + + operations = [ + migrations.CreateModel( + name='Collection', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=64)), + ], + ), + migrations.CreateModel( + name='VisualAsset', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=128)), + ('image', models.ImageField(upload_to='cards/')), + ('collection', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='api.collection')), + ], + options={ + 'ordering': ['name'], + }, + ), + ] diff --git a/api/migrations/0002_card_delete_visualasset.py b/api/migrations/0002_card_delete_visualasset.py new file mode 100644 index 0000000..4fbae0b --- /dev/null +++ b/api/migrations/0002_card_delete_visualasset.py @@ -0,0 +1,29 @@ +# Generated by Django 5.2.4 on 2025-07-13 11:17 + +import django.db.models.deletion +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('api', '0001_initial'), + ] + + operations = [ + migrations.CreateModel( + name='Card', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('name', models.CharField(max_length=128)), + ('image', models.ImageField(upload_to='cards/')), + ('collection', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='cards', related_query_name='card', to='api.collection')), + ], + options={ + 'ordering': ['name'], + }, + ), + migrations.DeleteModel( + name='VisualAsset', + ), + ] diff --git a/api/migrations/__init__.py b/api/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/api/models.py b/api/models.py new file mode 100644 index 0000000..b098a84 --- /dev/null +++ b/api/models.py @@ -0,0 +1,19 @@ +from django.db import models + + +class Collection(models.Model): + name = models.CharField(max_length=64) + + +class Card(models.Model): + name = models.CharField(max_length=128) + collection = models.ForeignKey( + Collection, + on_delete=models.CASCADE, + related_name="cards", + related_query_name="card", + ) + image = models.ImageField(upload_to="cards/") + + class Meta: + ordering = ["name"] diff --git a/api/serializers.py b/api/serializers.py new file mode 100644 index 0000000..47670e9 --- /dev/null +++ b/api/serializers.py @@ -0,0 +1,42 @@ +from rest_framework import serializers +from api.models import Card, Collection + + +class CardSerializer(serializers.ModelSerializer): + image_url = serializers.SerializerMethodField() + collection_name = serializers.CharField(write_only=True, required=False) + collection = serializers.PrimaryKeyRelatedField( + queryset=Collection.objects.all(), required=False + ) + + class Meta: + model = Card + fields = ["id", "name", "collection", "collection_name", "image", "image_url"] + + def create(self, validated_data): + collection_name = validated_data.pop("collection_name", None) + if collection_name: + collection, _ = Collection.objects.get_or_create(name=collection_name) + validated_data["collection"] = collection + elif not validated_data.get("collection"): + raise serializers.ValidationError( + { + "collection": "This field is required if collection_name is not provided." + } + ) + return super().create(validated_data) + + def get_image_url(self, obj): + request = self.context.get("request") + if obj.image: + url = obj.image.url + if request is not None: + return request.build_absolute_uri(url) + return url + return None + + +class CollectionSerializer(serializers.ModelSerializer): + class Meta: + model = Collection + fields = ["id", "name"] diff --git a/api/tests.py b/api/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/api/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/api/views.py b/api/views.py new file mode 100644 index 0000000..e511c67 --- /dev/null +++ b/api/views.py @@ -0,0 +1,16 @@ +from rest_framework import viewsets +from api.models import Card, Collection +from api.serializers import CardSerializer, CollectionSerializer +from django_filters.rest_framework import DjangoFilterBackend + + +class CardViewSet(viewsets.ModelViewSet): + queryset = Card.objects.all() + serializer_class = CardSerializer + filter_backends = [DjangoFilterBackend] + filterset_fields = ["collection__name"] + + +class CollectionViewSet(viewsets.ModelViewSet): + queryset = Collection.objects.all() + serializer_class = CollectionSerializer diff --git a/cards/FFXIV_Gaia_in-game_render.webp b/cards/FFXIV_Gaia_in-game_render.webp new file mode 100644 index 0000000..106221f Binary files /dev/null and b/cards/FFXIV_Gaia_in-game_render.webp differ diff --git a/cards/FFXIV_Gaia_in-game_render_B0Cardl.webp b/cards/FFXIV_Gaia_in-game_render_B0Cardl.webp new file mode 100644 index 0000000..106221f Binary files /dev/null and b/cards/FFXIV_Gaia_in-game_render_B0Cardl.webp differ diff --git a/cards/FFXIV_Gaia_in-game_render_zon8Tko.webp b/cards/FFXIV_Gaia_in-game_render_zon8Tko.webp new file mode 100644 index 0000000..106221f Binary files /dev/null and b/cards/FFXIV_Gaia_in-game_render_zon8Tko.webp differ diff --git a/manage.py b/manage.py new file mode 100644 index 0000000..4dfd6db --- /dev/null +++ b/manage.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python +"""Django's command-line utility for administrative tasks.""" +import os +import sys +from dotenv import load_dotenv + + +def main(): + load_dotenv() + + os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sop.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() diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..79a9938 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,17 @@ +asgiref==3.9.1 +Django==5.2.4 +django-cors-headers==4.7.0 +django-filter==25.1 +djangorestframework==3.16.0 +dotenv==0.9.9 +jmespath==1.0.1 +Markdown==3.8.2 +pillow==11.3.0 +psycopg2==2.9.10 +python-dateutil==2.9.0.post0 +python-dotenv==1.1.1 +s3transfer==0.13.0 +six==1.17.0 +sqlparse==0.5.3 +tzdata==2025.2 +urllib3==2.5.0 \ No newline at end of file diff --git a/sop/__init__.py b/sop/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/sop/asgi.py b/sop/asgi.py new file mode 100644 index 0000000..46bfeee --- /dev/null +++ b/sop/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for sop 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/5.2/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sop.settings') + +application = get_asgi_application() diff --git a/sop/settings.py b/sop/settings.py new file mode 100644 index 0000000..9cca6ae --- /dev/null +++ b/sop/settings.py @@ -0,0 +1,151 @@ +""" +Django settings for sop project. + +Generated by 'django-admin startproject' using Django 5.2.4. + +For more information on this file, see +https://docs.djangoproject.com/en/5.2/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/5.2/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/5.2/howto/deployment/checklist/ + +SECRET_KEY = os.environ.get("SECRET_KEY") +DEBUG = os.environ.get("DEBUG") == "True" + +ALLOWED_HOSTS = [] + +CORS_ALLOWED_ORIGINS = [ + "http://localhost:3000", + "https://sop.tdlaouer.fr", +] + + +# Application definition + +INSTALLED_APPS = [ + "django.contrib.admin", + "django.contrib.auth", + "django.contrib.contenttypes", + "django.contrib.sessions", + "django.contrib.messages", + "django.contrib.staticfiles", + "rest_framework", + "corsheaders", + "api", +] + +MIDDLEWARE = [ + "django.middleware.security.SecurityMiddleware", + "django.contrib.sessions.middleware.SessionMiddleware", + "corsheaders.middleware.CorsMiddleware", + "django.middleware.common.CommonMiddleware", + "django.middleware.csrf.CsrfViewMiddleware", + "django.contrib.auth.middleware.AuthenticationMiddleware", + "django.contrib.messages.middleware.MessageMiddleware", + "django.middleware.clickjacking.XFrameOptionsMiddleware", +] + +REST_FRAMEWORK = { + "DEFAULT_FILTER_BACKENDS": ["django_filters.rest_framework.DjangoFilterBackend"], +} + +ROOT_URLCONF = "sop.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 = "sop.wsgi.application" + + +# Database +# https://docs.djangoproject.com/en/5.2/ref/settings/#databases + +DATABASES = { + "default": { + "ENGINE": "django.db.backends.postgresql", + "NAME": f"{os.environ.get("DB_NAME")}", + "USER": f"{os.environ.get("DB_USER")}", + "PASSWORD": f"{os.environ.get("DB_PASSWD")}", + "HOST": f"{os.environ.get("DB_HOST")}", + "PORT": f"{os.environ.get("DB_PORT")}", + } +} + + +# Password validation +# https://docs.djangoproject.com/en/5.2/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.2/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/5.2/howto/static-files/ + +STATIC_URL = "static/" + +# Default primary key field type +# https://docs.djangoproject.com/en/5.2/ref/settings/#default-auto-field + +DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" + +# AWS credentianls + +""" AWS_ACCESS_KEY_ID = os.environ.get("AWS_ACCESS_KEY_ID") +AWS_SECRET_ACCESS_KEY = os.environ.get("AWS_SECRET_ACCESS_KEY") +AWS_STORAGE_BUCKET_NAME = os.environ.get("AWS_STORAGE_BUCKET_NAME") +AWS_S3_REGION_NAME = "eu-north-1" +AWS_S3_CUSTOM_DOMAIN = f"{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com" +AWS_DEFAULT_ACL = "public-read" +AWS_QUERYSTRING_AUTH = False +DEFAULT_FILE_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" """ + +MEDIA_ROOT = os.path.join(BASE_DIR, "media") +MEDIA_URL = os.environ.get("DJANGO_MEDIA_URL", "/media/") diff --git a/sop/urls.py b/sop/urls.py new file mode 100644 index 0000000..d3c60a6 --- /dev/null +++ b/sop/urls.py @@ -0,0 +1,32 @@ +""" +URL configuration for sop project. + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/5.2/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 include, path +from rest_framework import routers +from api.views import CardViewSet, CollectionViewSet +from django.conf.urls.static import static +from sop import settings + +router = routers.DefaultRouter() +router.register(r"cards", CardViewSet) +router.register(r"collections", CollectionViewSet) + +urlpatterns = [ + path("admin/", admin.site.urls), + path("api/", include(router.urls)), +] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) diff --git a/sop/wsgi.py b/sop/wsgi.py new file mode 100644 index 0000000..67a0f26 --- /dev/null +++ b/sop/wsgi.py @@ -0,0 +1,19 @@ +""" +WSGI config for sop 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/5.2/howto/deployment/wsgi/ +""" + +import os +from dotenv import load_dotenv + +from django.core.wsgi import get_wsgi_application + +load_dotenv(os.path.join(os.path.dirname(os.path.dirname(__file__)), ".env")) + +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sop.settings") + +application = get_wsgi_application()