first commit

This commit is contained in:
TDLaouer 2025-07-13 18:11:10 +02:00
commit a76455d5ad
22 changed files with 550 additions and 0 deletions

138
.gitignore vendored Normal file
View File

@ -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

1
README.md Normal file
View File

@ -0,0 +1 @@
# Smash or Pass with Django Rest Framework

0
api/__init__.py Normal file
View File

3
api/admin.py Normal file
View File

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

6
api/apps.py Normal file
View File

@ -0,0 +1,6 @@
from django.apps import AppConfig
class ApiConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'api'

View File

@ -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'],
},
),
]

View File

@ -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',
),
]

View File

19
api/models.py Normal file
View File

@ -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"]

42
api/serializers.py Normal file
View File

@ -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"]

3
api/tests.py Normal file
View File

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

16
api/views.py Normal file
View File

@ -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

Binary file not shown.

After

Width:  |  Height:  |  Size: 443 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 443 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 443 KiB

24
manage.py Normal file
View File

@ -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()

17
requirements.txt Normal file
View File

@ -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

0
sop/__init__.py Normal file
View File

16
sop/asgi.py Normal file
View File

@ -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()

151
sop/settings.py Normal file
View File

@ -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/")

32
sop/urls.py Normal file
View File

@ -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)

19
sop/wsgi.py Normal file
View File

@ -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()