This commit is contained in:
Viner Abubakirov
2025-12-10 14:18:04 +05:00
parent 9a16f9c9ca
commit 36fbd46909
28 changed files with 819 additions and 0 deletions

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 CoreConfig(AppConfig):
name = 'core'

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,3 @@
from django.shortcuts import render
# Create your views here.

22
music_storage/manage.py Executable 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', '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()

View File

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,8 @@
from django.urls import path
from music.views import TrackListView
urlpatterns = [
path("", TrackListView.as_view(), name="track_list"),
]

View File

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

View File

View File

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

View File

@@ -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",
}
}

View File

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

View File

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

View File

View File

@@ -0,0 +1,198 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Музыкальный сервис</title>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600&display=swap" rel="stylesheet">
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Inter', sans-serif;
background-color: #f8f9fa;
color: #333;
line-height: 1.6;
padding: 20px;
min-height: 100vh;
}
.container {
max-width: 800px;
margin: 0 auto;
background-color: #fff;
border-radius: 8px;
box-shadow: 0 2px 15px rgba(0,0,0,0.05);
padding: 30px;
}
header {
text-align: center;
margin-bottom: 30px;
padding-bottom: 20px;
border-bottom: 1px solid #eee;
}
h1 {
font-weight: 500;
font-size: 2rem;
color: #2c3e50;
margin-bottom: 10px;
}
.subtitle {
color: #7f8c8d;
font-size: 1rem;
}
.track-list {
list-style: none;
}
.track-item {
padding: 20px 0;
border-bottom: 1px solid #f0f0f0;
display: flex;
align-items: center;
gap: 20px;
}
.track-item:last-child {
border-bottom: none;
}
.track-number {
width: 30px;
height: 30px;
display: flex;
align-items: center;
justify-content: center;
background-color: #e9ecef;
border-radius: 50%;
font-size: 0.9rem;
color: #6c757d;
flex-shrink: 0;
}
.track-info {
flex: 1;
}
.track-title {
font-weight: 500;
color: #2c3e50;
margin-bottom: 5px;
}
.track-artist {
color: #7f8c8d;
font-size: 0.9rem;
}
.player-container {
background-color: #f8f9fa;
border-radius: 6px;
padding: 15px;
margin-top: 10px;
}
.audio-player {
width: 100%;
margin: 0;
border-radius: 4px;
background-color: #fff;
}
.player-controls {
display: flex;
align-items: center;
justify-content: space-between;
padding: 10px 0;
}
.player-time {
font-size: 0.8rem;
color: #7f8c8d;
}
.empty-state {
text-align: center;
padding: 50px 20px;
color: #7f8c8d;
}
.empty-state i {
font-size: 3rem;
margin-bottom: 15px;
color: #bdc3c7;
}
footer {
text-align: center;
margin-top: 40px;
padding-top: 20px;
border-top: 1px solid #eee;
color: #7f8c8d;
font-size: 0.9rem;
}
@media (max-width: 600px) {
.container {
padding: 20px 15px;
}
.track-item {
flex-direction: column;
align-items: flex-start;
gap: 10px;
}
.track-number {
margin-right: 10px;
}
}
</style>
</head>
<body>
<div class="container">
<header>
<h1>Музыкальный сервис</h1>
<p class="subtitle">Ваша коллекция треков</p>
</header>
<ul class="track-list">
{% if tracks %}
{% for track in tracks %}
<li class="track-item">
<div class="track-number">{{ forloop.counter }}</div>
<div class="track-info">
<h3 class="track-title">{{ track.title }}</h3>
<p class="track-artist">Исполнитель: {{ track.artist }}</p>
<div class="player-container">
<audio class="audio-player" controls>
<source src="{{ track.file.url }}" type="audio/mpeg">
Ваш браузер не поддерживает аудио.
</audio>
</div>
</div>
</li>
{% endfor %}
{% else %}
<div class="empty-state">
<i class="fas fa-music"></i>
<p>Нет добавленных треков</p>
</div>
{% endif %}
</ul>
<footer>
<p>© 2023 Музыкальный сервис</p>
</footer>
</div>
</body>
</html>