diff --git a/.python-version b/.python-version new file mode 100644 index 0000000..24ee5b1 --- /dev/null +++ b/.python-version @@ -0,0 +1 @@ +3.13 diff --git a/music_storage/core/__init__.py b/music_storage/core/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/music_storage/core/admin.py b/music_storage/core/admin.py new file mode 100644 index 0000000..8c38f3f --- /dev/null +++ b/music_storage/core/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/music_storage/core/apps.py b/music_storage/core/apps.py new file mode 100644 index 0000000..26f78a8 --- /dev/null +++ b/music_storage/core/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class CoreConfig(AppConfig): + name = 'core' diff --git a/music_storage/core/middleware/current_request.py b/music_storage/core/middleware/current_request.py new file mode 100644 index 0000000..cccf745 --- /dev/null +++ b/music_storage/core/middleware/current_request.py @@ -0,0 +1,34 @@ +import threading +from django.utils.deprecation import MiddlewareMixin + + +_thread_local = threading.local() + + +def get_current_request(): + """Retrieve the current request stored in thread-local storage.""" + return getattr(_thread_local, "request", None) + + +def get_current_user(): + """Retrieve the user from the current request.""" + request = get_current_request() + if request: + return getattr(request, "user", None) + return None + + +class CurrentRequestMiddleware(MiddlewareMixin): + """Middleware to store the current request in thread-local storage. + + Args: + MiddlewareMixin : Base class for Django middleware. + """ + + def process_request(self, request): + _thread_local.request = request + + def process_response(self, request, response): + if hasattr(_thread_local, "request"): + del _thread_local.request + return response diff --git a/music_storage/core/migrations/__init__.py b/music_storage/core/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/music_storage/core/models.py b/music_storage/core/models.py new file mode 100644 index 0000000..e10fb61 --- /dev/null +++ b/music_storage/core/models.py @@ -0,0 +1,42 @@ +from django.db import models +from django.contrib.auth import get_user_model +from core.middleware.current_request import get_current_user + + +UserModel = get_user_model() + + +class BaseModel(models.Model): + """Abstract base model that includes created_by and updated_by fields. + + The fields are automatically populated with the current user from the request. + """ + + created_by = models.ForeignKey( + UserModel, + on_delete=models.SET_NULL, + null=True, + blank=True, + related_name="%(class)s_created", + editable=False, + ) + updated_by = models.ForeignKey( + UserModel, + on_delete=models.SET_NULL, + null=True, + blank=True, + related_name="%(class)s_updated", + editable=False, + ) + created_at = models.DateTimeField(auto_now_add=True) + updated_at = models.DateTimeField(auto_now=True) + + class Meta: + abstract = True + + def save(self, *args, **kwargs): + current_user = get_current_user() + if not self.pk and not self.created_by: + self.created_by = current_user + self.updated_by = current_user + super().save(*args, **kwargs) diff --git a/music_storage/core/tests.py b/music_storage/core/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/music_storage/core/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/music_storage/core/views.py b/music_storage/core/views.py new file mode 100644 index 0000000..91ea44a --- /dev/null +++ b/music_storage/core/views.py @@ -0,0 +1,3 @@ +from django.shortcuts import render + +# Create your views here. diff --git a/music_storage/manage.py b/music_storage/manage.py new file mode 100755 index 0000000..522c782 --- /dev/null +++ b/music_storage/manage.py @@ -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', 'music_storage.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/music_storage/music/__init__.py b/music_storage/music/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/music_storage/music/admin.py b/music_storage/music/admin.py new file mode 100644 index 0000000..2378241 --- /dev/null +++ b/music_storage/music/admin.py @@ -0,0 +1,29 @@ +from django.contrib import admin + +from music.models import Track, Album, Artist + + +@admin.register(Track) +class TrackAdmin(admin.ModelAdmin): + class Media: + js = ('admin/js/upload_progress.js',) + css = { + 'all': ('admin/css/upload_progress.css',) + } + + list_display = ("artist__name", "title", "created_by", "created_at") + search_fields = ("title", "artist__name", "album__name") + list_filter = ("artist__name",) + + +@admin.register(Album) +class AlbumAdmin(admin.ModelAdmin): + list_display = ("artist__name", "name") + search_fields = ("artist__name", "name") + list_filter = ("artist__name",) + + +@admin.register(Artist) +class ArtistAdmin(admin.ModelAdmin): + list_display = ("name",) + search_fields = ("name",) diff --git a/music_storage/music/apps.py b/music_storage/music/apps.py new file mode 100644 index 0000000..d909c7f --- /dev/null +++ b/music_storage/music/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class MusicConfig(AppConfig): + name = 'music' diff --git a/music_storage/music/migrations/0001_initial.py b/music_storage/music/migrations/0001_initial.py new file mode 100644 index 0000000..df7b73c --- /dev/null +++ b/music_storage/music/migrations/0001_initial.py @@ -0,0 +1,63 @@ +# Generated by Django 6.0 on 2025-12-10 07:50 + +import django.db.models.deletion +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name='Artist', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('name', models.CharField(max_length=200)), + ('created_by', models.ForeignKey(blank=True, editable=False, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='%(class)s_created', to=settings.AUTH_USER_MODEL)), + ('updated_by', models.ForeignKey(blank=True, editable=False, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='%(class)s_updated', to=settings.AUTH_USER_MODEL)), + ], + options={ + 'abstract': False, + }, + ), + migrations.CreateModel( + name='Album', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('name', models.CharField(max_length=200)), + ('created_by', models.ForeignKey(blank=True, editable=False, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='%(class)s_created', to=settings.AUTH_USER_MODEL)), + ('updated_by', models.ForeignKey(blank=True, editable=False, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='%(class)s_updated', to=settings.AUTH_USER_MODEL)), + ('artist', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='music.artist')), + ], + options={ + 'abstract': False, + }, + ), + migrations.CreateModel( + name='Track', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('updated_at', models.DateTimeField(auto_now=True)), + ('title', models.CharField(max_length=200)), + ('file', models.FileField(upload_to='music/')), + ('album', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.SET_DEFAULT, to='music.album')), + ('artist', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='music.artist')), + ('created_by', models.ForeignKey(blank=True, editable=False, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='%(class)s_created', to=settings.AUTH_USER_MODEL)), + ('updated_by', models.ForeignKey(blank=True, editable=False, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='%(class)s_updated', to=settings.AUTH_USER_MODEL)), + ], + options={ + 'abstract': False, + }, + ), + ] diff --git a/music_storage/music/migrations/__init__.py b/music_storage/music/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/music_storage/music/models.py b/music_storage/music/models.py new file mode 100644 index 0000000..ec1d6c7 --- /dev/null +++ b/music_storage/music/models.py @@ -0,0 +1,27 @@ +from django.db import models +from core.models import BaseModel + + +class Artist(BaseModel): + name = models.CharField(max_length=200) + + def __str__(self): + return f"{self.name}" + + +class Album(BaseModel): + artist = models.ForeignKey(Artist, on_delete=models.CASCADE) + name = models.CharField(max_length=200) + + def __str__(self): + return f"{self.artist} - {self.name}" + + +class Track(BaseModel): + title = models.CharField(max_length=200) + artist = models.ForeignKey(Artist, on_delete=models.CASCADE) + album = models.ForeignKey(Album, blank=True, null=True, default=None, on_delete=models.SET_DEFAULT) + file = models.FileField(upload_to="music/") + + def __str__(self): + return f"{self.artist} - {self.title}" diff --git a/music_storage/music/tests.py b/music_storage/music/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/music_storage/music/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/music_storage/music/urls.py b/music_storage/music/urls.py new file mode 100644 index 0000000..e4fcd8f --- /dev/null +++ b/music_storage/music/urls.py @@ -0,0 +1,8 @@ +from django.urls import path + +from music.views import TrackListView + + +urlpatterns = [ + path("", TrackListView.as_view(), name="track_list"), +] diff --git a/music_storage/music/views.py b/music_storage/music/views.py new file mode 100644 index 0000000..41bda82 --- /dev/null +++ b/music_storage/music/views.py @@ -0,0 +1,11 @@ +from django import views as django_views +from django.shortcuts import render +from django.http.request import HttpRequest + +from music.models import Track + + +class TrackListView(django_views.View): + def get(self, request: HttpRequest, *args, **kwargs): + tracks = Track.objects.all() + return render(request, "music/track_list.html", {"tracks": tracks}) diff --git a/music_storage/music_storage/__init__.py b/music_storage/music_storage/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/music_storage/music_storage/asgi.py b/music_storage/music_storage/asgi.py new file mode 100644 index 0000000..07dc2bc --- /dev/null +++ b/music_storage/music_storage/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for music_storage 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', 'music_storage.settings') + +application = get_asgi_application() diff --git a/music_storage/music_storage/settings.py b/music_storage/music_storage/settings.py new file mode 100644 index 0000000..76b8d3f --- /dev/null +++ b/music_storage/music_storage/settings.py @@ -0,0 +1,144 @@ +""" +Django settings for music_storage project. + +Generated by 'django-admin startproject' using Django 6.0. + +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 + +# 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-=*m3r8o(%h3@7tl2-((k&t%%k)m&*b)i^4w#ixl0i$#6!gtg&+' + +# 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', + # External apps + 'storages', + # Custom apps + 'core', + 'music', +] + +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', + # Custom middlewares + "core.middleware.current_request.CurrentRequestMiddleware", +] + +ROOT_URLCONF = 'music_storage.urls' + +TEMPLATES = [ + { + 'BACKEND': 'django.template.backends.django.DjangoTemplates', + 'DIRS': [BASE_DIR / 'templates',], + '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 = 'music_storage.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', + } +} + + +# 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/' + +STORAGES = { + # default storage for user uploads + "default": { + "BACKEND": "storages.backends.s3.S3Storage", + "OPTIONS": { + "access_key": "admin", + "secret_key": "admintestpassword", + "bucket_name": "dev-bucket", + "endpoint_url": "http://192.168.88.252:9000", + "region_name": "us-east-1", + "signature_version": "s3v4", + } + }, + + # static files — если нужно, может остаться на FileSystemStorage + "staticfiles": { + "BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage", + } +} diff --git a/music_storage/music_storage/urls.py b/music_storage/music_storage/urls.py new file mode 100644 index 0000000..3524e89 --- /dev/null +++ b/music_storage/music_storage/urls.py @@ -0,0 +1,23 @@ +""" +URL configuration for music_storage 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("music.urls")), +] diff --git a/music_storage/music_storage/wsgi.py b/music_storage/music_storage/wsgi.py new file mode 100644 index 0000000..29605f4 --- /dev/null +++ b/music_storage/music_storage/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for music_storage 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', 'music_storage.settings') + +application = get_wsgi_application() diff --git a/music_storage/templates/base.html b/music_storage/templates/base.html new file mode 100644 index 0000000..e69de29 diff --git a/music_storage/templates/music/track_list.html b/music_storage/templates/music/track_list.html new file mode 100644 index 0000000..ed0a1c2 --- /dev/null +++ b/music_storage/templates/music/track_list.html @@ -0,0 +1,198 @@ + + +
+ + +Ваша коллекция треков
+Исполнитель: {{ track.artist }}
+ +Нет добавленных треков
+