Initial
This commit is contained in:
22
backend/Dockerfile
Executable file
22
backend/Dockerfile
Executable file
@@ -0,0 +1,22 @@
|
||||
FROM python:3.11-alpine
|
||||
|
||||
EXPOSE 8000
|
||||
|
||||
# install base system
|
||||
RUN apk add --no-cache gcc libc-dev linux-headers
|
||||
RUN pip install --upgrade pip
|
||||
RUN pip install uvicorn gunicorn
|
||||
|
||||
# install requirements
|
||||
WORKDIR /django_project
|
||||
COPY ./requirements.txt .
|
||||
RUN pip install -r requirements.txt
|
||||
|
||||
# then scripts (likely wont change often)
|
||||
ENV PATH="/scripts:/py/bin:$PATH"
|
||||
COPY --chmod=700 ./scripts /scripts
|
||||
|
||||
# finally copy app (likely will invalidate cache)
|
||||
COPY . .
|
||||
|
||||
CMD ["run.sh"]
|
||||
0
backend/app/__init__.py
Normal file
0
backend/app/__init__.py
Normal file
71
backend/app/admin.py
Normal file
71
backend/app/admin.py
Normal file
@@ -0,0 +1,71 @@
|
||||
from django.conf import settings
|
||||
from django.contrib import admin
|
||||
from django.contrib.auth.models import Group # , User
|
||||
from django.utils.html import format_html
|
||||
|
||||
from app.models import Audiofile, Category, Content, Place
|
||||
|
||||
# admin.site.register(Place, )
|
||||
|
||||
#############################
|
||||
# Django defaults
|
||||
#############################
|
||||
|
||||
admin.site.site_header = 'Klangkarte-Verwaltung' # top-most title
|
||||
admin.site.index_title = 'Klangkarte' # title at root
|
||||
admin.site.site_title = 'Klangkarte-Verwaltung' # suffix to <title>
|
||||
|
||||
admin.site.unregister(Group)
|
||||
# admin.site.unregister(User)
|
||||
|
||||
|
||||
#############################
|
||||
# App adjustments
|
||||
#############################
|
||||
|
||||
|
||||
@admin.register(Audiofile)
|
||||
class AudiofileAdmin(admin.ModelAdmin):
|
||||
list_display = ['desc', 'media_url', 'created']
|
||||
search_fields = ['desc']
|
||||
|
||||
@admin.display(description='URL')
|
||||
def media_url(self, obj: 'Audiofile'):
|
||||
return settings.MEDIA_URL + obj.url
|
||||
|
||||
|
||||
@admin.register(Category)
|
||||
class CategoryAdmin(admin.ModelAdmin):
|
||||
list_display = ['name', 'color_dot', 'sort', 'places_count']
|
||||
search_fields = ['name']
|
||||
|
||||
class Media:
|
||||
css = {'all': ['admin/admin.css']}
|
||||
|
||||
@admin.display(description='Orte')
|
||||
def places_count(self, obj: 'Category'):
|
||||
return obj.places.count()
|
||||
|
||||
@admin.display(description='Farbe')
|
||||
def color_dot(self, obj: 'Category'):
|
||||
return format_html(
|
||||
'<span class="color-dot" style="background:{};color:{}">{}</span>',
|
||||
obj.color,
|
||||
'#fff' if obj.fg_color_white else '#000',
|
||||
obj.color.upper())
|
||||
|
||||
|
||||
@admin.register(Content)
|
||||
class ContentAdmin(admin.ModelAdmin):
|
||||
list_display = ['title', 'body']
|
||||
search_fields = ['title', 'body']
|
||||
|
||||
def get_readonly_fields(self, request, obj=None):
|
||||
return ['key'] if obj else []
|
||||
|
||||
|
||||
@admin.register(Place)
|
||||
class PlaceAdmin(admin.ModelAdmin):
|
||||
list_display = ['title', 'category', 'sort', 'created']
|
||||
search_fields = ['title']
|
||||
list_filter = ['category']
|
||||
6
backend/app/apps.py
Normal file
6
backend/app/apps.py
Normal file
@@ -0,0 +1,6 @@
|
||||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class AppConfig(AppConfig):
|
||||
default_auto_field = 'django.db.models.BigAutoField'
|
||||
name = 'app'
|
||||
85
backend/app/migrations/0001_initial.py
Normal file
85
backend/app/migrations/0001_initial.py
Normal file
@@ -0,0 +1,85 @@
|
||||
# Generated by Django 4.2.13 on 2024-06-22 15:46
|
||||
|
||||
import app.models.audiofile
|
||||
import app.models.place
|
||||
import colorfield.fields
|
||||
import common.form.audio_file
|
||||
import common.form.img_with_preview
|
||||
import map_location.fields
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
import tinymce.models
|
||||
import uuid
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
initial = True
|
||||
|
||||
dependencies = [
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='Audiofile',
|
||||
fields=[
|
||||
('key', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('audio', common.form.audio_file.AudioFileField(upload_to=app.models.audiofile.overwrite_audio, verbose_name='Audio')),
|
||||
('desc', models.CharField(max_length=200, verbose_name='Beschreibung')),
|
||||
('created', models.DateTimeField(auto_now_add=True, verbose_name='Erstellt')),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'Audiodatei',
|
||||
'verbose_name_plural': 'Audiodateien',
|
||||
'ordering': ('-created',),
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='Category',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('name', models.CharField(max_length=100, verbose_name='Name')),
|
||||
('color', colorfield.fields.ColorField(default='#3388ff', image_field=None, max_length=7, samples=None, verbose_name='Farbe')),
|
||||
('fg_color_white', models.BooleanField(default=False, verbose_name='Textfarbe Weiß')),
|
||||
('sort', models.IntegerField(default=0, verbose_name='Sortierung')),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'Kategorie',
|
||||
'verbose_name_plural': 'Kategorien',
|
||||
'ordering': ('sort',),
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='Content',
|
||||
fields=[
|
||||
('key', models.SlugField(primary_key=True, serialize=False, unique=True, verbose_name='ID')),
|
||||
('title', models.CharField(max_length=100, verbose_name='Titel')),
|
||||
('body', tinymce.models.HTMLField(verbose_name='Inhalt')),
|
||||
('wide', models.BooleanField(verbose_name='Breiteres Fenster')),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'Text',
|
||||
'verbose_name_plural': 'Texte',
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='Place',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('sort', models.IntegerField(default=0, verbose_name='Sortierung')),
|
||||
('isExtended', models.BooleanField(verbose_name='Bis 1.1.2025 verstecken')),
|
||||
('title', models.CharField(max_length=100, verbose_name='Titel')),
|
||||
('image', common.form.img_with_preview.FileWithImagePreview(blank=True, null=True, upload_to=app.models.place.overwrite_img_upload, verbose_name='Bild')),
|
||||
('audio', common.form.audio_file.AudioFileField(blank=True, null=True, upload_to=app.models.place.overwrite_audio_upload, verbose_name='Audio')),
|
||||
('location', map_location.fields.LocationField(blank=True, null=True, verbose_name='Position')),
|
||||
('description', tinymce.models.HTMLField(verbose_name='Beschreibung')),
|
||||
('created', models.DateTimeField(auto_now_add=True, verbose_name='Erstellt')),
|
||||
('category', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='places', to='app.category', verbose_name='Kategorie')),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'Ort',
|
||||
'verbose_name_plural': 'Orte',
|
||||
'ordering': ('sort',),
|
||||
},
|
||||
),
|
||||
]
|
||||
0
backend/app/migrations/__init__.py
Normal file
0
backend/app/migrations/__init__.py
Normal file
4
backend/app/models/__init__.py
Normal file
4
backend/app/models/__init__.py
Normal file
@@ -0,0 +1,4 @@
|
||||
from .audiofile import Audiofile # noqa: F401
|
||||
from .category import Category # noqa: F401
|
||||
from .content import Content # noqa: F401
|
||||
from .place import Place # noqa: F401
|
||||
45
backend/app/models/audiofile.py
Normal file
45
backend/app/models/audiofile.py
Normal file
@@ -0,0 +1,45 @@
|
||||
from django.conf import settings
|
||||
from django.db import models
|
||||
from django.db.models.signals import post_delete
|
||||
from django.dispatch import receiver
|
||||
|
||||
import os
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
from common.form.audio_file import AudioFileField
|
||||
|
||||
|
||||
def overwrite_audio(instance: 'Audiofile', filename: str):
|
||||
if instance.path.is_file():
|
||||
os.remove(instance.path)
|
||||
return instance.url
|
||||
|
||||
|
||||
class Audiofile(models.Model):
|
||||
key = models.UUIDField('ID', primary_key=True, default=uuid.uuid4,
|
||||
editable=False)
|
||||
audio = AudioFileField('Audio', upload_to=overwrite_audio)
|
||||
desc = models.CharField('Beschreibung', max_length=200)
|
||||
created = models.DateTimeField('Erstellt', auto_now_add=True)
|
||||
|
||||
class Meta:
|
||||
verbose_name = 'Audiodatei'
|
||||
verbose_name_plural = 'Audiodateien'
|
||||
ordering = ('-created',)
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.desc
|
||||
|
||||
@property
|
||||
def path(self) -> Path:
|
||||
return settings.MEDIA_ROOT / 'audio' / f'{self.pk}.mp3'
|
||||
|
||||
@property
|
||||
def url(self) -> str:
|
||||
return f'audio/{self.pk}.mp3'
|
||||
|
||||
|
||||
@receiver(post_delete, sender=Audiofile)
|
||||
def on_delete_Audiofile(sender, instance: 'Audiofile', using, **kwargs):
|
||||
os.remove(instance.path)
|
||||
55
backend/app/models/category.py
Normal file
55
backend/app/models/category.py
Normal file
@@ -0,0 +1,55 @@
|
||||
from django.conf import settings
|
||||
from django.db import models
|
||||
from django.db.models.signals import post_delete
|
||||
from django.dispatch import receiver
|
||||
|
||||
import json
|
||||
from colorfield.fields import ColorField
|
||||
|
||||
import typing
|
||||
if typing.TYPE_CHECKING:
|
||||
from app.models.place import Place
|
||||
|
||||
|
||||
class Category(models.Model):
|
||||
name = models.CharField('Name', max_length=100)
|
||||
color = ColorField('Farbe', default='#3388ff', max_length=7)
|
||||
fg_color_white = models.BooleanField('Textfarbe Weiß', default=False)
|
||||
sort = models.IntegerField('Sortierung', default=0)
|
||||
|
||||
places: 'models.QuerySet[Place]'
|
||||
|
||||
class Meta:
|
||||
verbose_name = 'Kategorie'
|
||||
verbose_name_plural = 'Kategorien'
|
||||
ordering = ('sort',)
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.name
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
rv = super().save(*args, **kwargs)
|
||||
Category.update_json()
|
||||
return rv
|
||||
|
||||
@staticmethod
|
||||
def update_json():
|
||||
with open(settings.MEDIA_ROOT / 'categories.json', 'w') as fp:
|
||||
json.dump(Category.asJson(), fp)
|
||||
|
||||
@staticmethod
|
||||
def asJson() -> 'list[dict[str, str]]':
|
||||
rv = []
|
||||
for x in Category.objects.all():
|
||||
rv.append({
|
||||
'id': x.pk,
|
||||
'name': x.name,
|
||||
'color': x.color,
|
||||
'inv': x.fg_color_white,
|
||||
})
|
||||
return rv
|
||||
|
||||
|
||||
@receiver(post_delete, sender=Category)
|
||||
def on_delete_Audiofile(sender, instance: 'Category', using, **kwargs):
|
||||
Category.update_json()
|
||||
40
backend/app/models/content.py
Normal file
40
backend/app/models/content.py
Normal file
@@ -0,0 +1,40 @@
|
||||
from django.conf import settings
|
||||
from django.db import models
|
||||
|
||||
import json
|
||||
from tinymce.models import HTMLField
|
||||
|
||||
|
||||
class Content(models.Model):
|
||||
key = models.SlugField('ID', primary_key=True, unique=True)
|
||||
title = models.CharField('Titel', max_length=100)
|
||||
body = HTMLField('Inhalt')
|
||||
wide = models.BooleanField('Breiteres Fenster')
|
||||
|
||||
class Meta:
|
||||
verbose_name = 'Text'
|
||||
verbose_name_plural = 'Texte'
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.title
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
rv = super().save(*args, **kwargs)
|
||||
self.update_json()
|
||||
return rv
|
||||
|
||||
def delete(self, *args, **kwargs):
|
||||
rv = super().delete(*args, **kwargs)
|
||||
self.update_json()
|
||||
return rv
|
||||
|
||||
def update_json(self):
|
||||
with open(settings.MEDIA_ROOT / 'text.json', 'w') as fp:
|
||||
json.dump(self.asJson(), fp)
|
||||
|
||||
@staticmethod
|
||||
def asJson() -> 'dict[str, str]':
|
||||
rv = {}
|
||||
for x in Content.objects.all():
|
||||
rv[x.pk] = {'title': x.title, 'body': x.body, 'wide': x.wide}
|
||||
return rv
|
||||
131
backend/app/models/place.py
Normal file
131
backend/app/models/place.py
Normal file
@@ -0,0 +1,131 @@
|
||||
from django.conf import settings
|
||||
from django.db import models
|
||||
from django.db.models.signals import post_delete
|
||||
from django.dispatch import receiver
|
||||
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
from PIL import Image, ImageOps
|
||||
from tinymce.models import HTMLField
|
||||
from map_location.fields import LocationField
|
||||
# default_app_config = 'map_location.apps.MapLocationConfig'
|
||||
|
||||
from app.models.category import Category
|
||||
from common.form.audio_file import AudioFileField
|
||||
from common.form.img_with_preview import FileWithImagePreview
|
||||
|
||||
|
||||
def overwrite_img_upload(instance: 'Place', filename: str):
|
||||
path = instance.fixed_os_path('img.jpg')
|
||||
if path.is_file():
|
||||
os.remove(path)
|
||||
return instance.fixed_save_url('img.jpg')
|
||||
|
||||
|
||||
def overwrite_audio_upload(instance: 'Place', filename: str):
|
||||
path = instance.fixed_os_path('audio.mp3')
|
||||
if path.is_file():
|
||||
os.remove(path)
|
||||
return instance.fixed_save_url('audio.mp3')
|
||||
|
||||
|
||||
class Place(models.Model):
|
||||
category: 'models.ForeignKey[Category]' = models.ForeignKey(
|
||||
'Category', on_delete=models.CASCADE, related_name='places',
|
||||
verbose_name='Kategorie')
|
||||
|
||||
sort = models.IntegerField('Sortierung', default=0)
|
||||
isExtended = models.BooleanField('Bis 1.1.2025 verstecken')
|
||||
title = models.CharField('Titel', max_length=100)
|
||||
image = FileWithImagePreview('Bild', blank=True, null=True,
|
||||
upload_to=overwrite_img_upload)
|
||||
# help_text='Ideal: 600 x 400 px (JPEG oder PNG)'
|
||||
audio = AudioFileField('Audio', blank=True, null=True,
|
||||
upload_to=overwrite_audio_upload)
|
||||
location = LocationField('Position', blank=True, null=True, options={
|
||||
'map': {
|
||||
'center': [49.895, 10.890],
|
||||
'zoom': 14,
|
||||
},
|
||||
})
|
||||
description = HTMLField('Beschreibung')
|
||||
created = models.DateTimeField('Erstellt', auto_now_add=True)
|
||||
|
||||
class Meta:
|
||||
verbose_name = 'Ort'
|
||||
verbose_name_plural = 'Orte'
|
||||
ordering = ('sort',)
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.title
|
||||
|
||||
def fixed_os_path(self, name: str) -> Path:
|
||||
return settings.MEDIA_ROOT / str(self.pk) / name
|
||||
|
||||
def fixed_save_url(self, name: str) -> str:
|
||||
if self.pk is None:
|
||||
next_id = Place.objects.count() + 1
|
||||
return f'{next_id}/{name}'
|
||||
return f'{self.pk}/{name}'
|
||||
|
||||
@property
|
||||
def cover_image_url(self) -> 'str|None':
|
||||
if self.image:
|
||||
return self.image.url.replace('img.jpg', 'cov.jpg')
|
||||
return None
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
rv = super().save(*args, **kwargs)
|
||||
self.update_cover_image()
|
||||
Place.update_json()
|
||||
return rv
|
||||
|
||||
# def delete(self, *args, **kwargs):
|
||||
# theId = str(self.pk)
|
||||
# rv = super().delete(*args, **kwargs)
|
||||
# shutil.rmtree(settings.MEDIA_ROOT / theId, ignore_errors=True)
|
||||
# self.update_json()
|
||||
# return rv
|
||||
|
||||
def update_cover_image(self):
|
||||
path = self.fixed_os_path('cov.jpg')
|
||||
if self.image:
|
||||
img = Image.open(self.image.path)
|
||||
thumb = ImageOps.fit(img, (600, 400))
|
||||
# img.thumbnail((600, 400))
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
thumb.save(path, 'jpeg')
|
||||
else:
|
||||
if path.exists():
|
||||
os.remove(path)
|
||||
|
||||
@staticmethod
|
||||
def update_json():
|
||||
with open(settings.MEDIA_ROOT / 'places.json', 'w') as fp:
|
||||
json.dump(Place.asJson(), fp)
|
||||
|
||||
@staticmethod
|
||||
def asJson() -> 'list[dict[str, str]]':
|
||||
rv = []
|
||||
for x in Place.objects.all():
|
||||
rv.append({
|
||||
'id': x.pk,
|
||||
'name': x.title,
|
||||
'loc': [round(x.location.lat, 6),
|
||||
round(x.location.long, 6)] if x.location else None,
|
||||
'cat': x.category.pk,
|
||||
'cov': x.cover_image_url,
|
||||
'img': x.image.url if x.image else None,
|
||||
'audio': x.audio.url if x.audio else None,
|
||||
'later': x.isExtended,
|
||||
'desc': x.description,
|
||||
})
|
||||
return rv
|
||||
|
||||
|
||||
@receiver(post_delete, sender=Place)
|
||||
def on_delete_Audiofile(sender, instance: 'Place', using, **kwargs):
|
||||
shutil.rmtree(settings.MEDIA_ROOT / str(instance.pk), ignore_errors=True)
|
||||
Place.update_json()
|
||||
5
backend/app/static/admin/admin.css
Normal file
5
backend/app/static/admin/admin.css
Normal file
@@ -0,0 +1,5 @@
|
||||
.color-dot {
|
||||
font-family: monospace;
|
||||
border-radius: 4px;
|
||||
padding: 2px 8px;
|
||||
}
|
||||
0
backend/common/__init__.py
Normal file
0
backend/common/__init__.py
Normal file
70
backend/common/form/audio_file.py
Normal file
70
backend/common/form/audio_file.py
Normal file
@@ -0,0 +1,70 @@
|
||||
from django import forms
|
||||
from django.conf import settings
|
||||
from django.contrib.admin.widgets import AdminFileWidget
|
||||
from django.core.validators import FileExtensionValidator
|
||||
from django.db import models
|
||||
from django.forms import FileInput, widgets
|
||||
|
||||
from common.validators import MaxFilesizeValidator, readableToInt
|
||||
|
||||
MAX_UPLOAD_SIZE = '20 MB'
|
||||
|
||||
|
||||
class AudioFileWidget(widgets.ClearableFileInput):
|
||||
template_name = 'forms/audio-file.html'
|
||||
|
||||
class Media:
|
||||
js = ['admin/file-upload-validator.js']
|
||||
|
||||
def get_context(self, name, value, attrs):
|
||||
context = super().get_context(name, value, attrs)
|
||||
context['MEDIA_URL'] = settings.MEDIA_URL
|
||||
return context
|
||||
|
||||
|
||||
class AudioField(forms.FileField):
|
||||
widget = AudioFileWidget
|
||||
default_validators = [
|
||||
FileExtensionValidator(['mp3']),
|
||||
MaxFilesizeValidator(MAX_UPLOAD_SIZE)
|
||||
]
|
||||
|
||||
def widget_attrs(self, widget):
|
||||
attrs = super().widget_attrs(widget)
|
||||
if isinstance(widget, FileInput) and 'accept' not in widget.attrs:
|
||||
attrs.setdefault('accept', 'audio/mpeg') # audio/*
|
||||
if isinstance(widget, AudioFileWidget):
|
||||
attrs.update({
|
||||
'data-upload-limit': readableToInt(MAX_UPLOAD_SIZE),
|
||||
'data-upload-limit-str': MAX_UPLOAD_SIZE,
|
||||
'onchange': 'validate_upload_limit(this)',
|
||||
})
|
||||
return attrs
|
||||
|
||||
|
||||
class AudioFileField(models.FileField):
|
||||
__del_file_on_save = False
|
||||
|
||||
def formfield(self, **kwargs):
|
||||
if kwargs['widget'] is AdminFileWidget:
|
||||
# Override admin widget. Defined by AudioField anyway
|
||||
del kwargs['widget']
|
||||
return super().formfield(**{'form_class': AudioField, **kwargs})
|
||||
|
||||
def save_form_data(self, instance, data):
|
||||
if data is False:
|
||||
self.__del_file_on_save = True
|
||||
super().save_form_data(instance, data)
|
||||
|
||||
def pre_save(self, model_instance, add):
|
||||
if self.__del_file_on_save:
|
||||
self.__del_file_on_save = False
|
||||
self.deletePreviousFile(model_instance)
|
||||
return super().pre_save(model_instance, add)
|
||||
|
||||
def deletePreviousFile(self, instance: models.Model):
|
||||
if not instance.pk:
|
||||
return
|
||||
prev = instance.__class__.objects.get(pk=instance.pk)
|
||||
fileField = getattr(prev, self.attname)
|
||||
fileField.delete(save=False)
|
||||
67
backend/common/form/img_with_preview.py
Normal file
67
backend/common/form/img_with_preview.py
Normal file
@@ -0,0 +1,67 @@
|
||||
from django import forms
|
||||
from django.conf import settings
|
||||
from django.contrib.admin.widgets import AdminFileWidget
|
||||
from django.core.validators import FileExtensionValidator
|
||||
from django.db import models
|
||||
from django.forms import FileInput, widgets
|
||||
|
||||
from common.validators import MaxFilesizeValidator, readableToInt
|
||||
|
||||
MAX_UPLOAD_SIZE = '312 KB'
|
||||
|
||||
|
||||
class ImageFileWidget(widgets.ClearableFileInput):
|
||||
template_name = 'forms/img-with-preview.html'
|
||||
|
||||
def get_context(self, name, value, attrs):
|
||||
context = super().get_context(name, value, attrs)
|
||||
context['MEDIA_URL'] = settings.MEDIA_URL
|
||||
return context
|
||||
|
||||
|
||||
class ImgField(forms.FileField):
|
||||
widget = ImageFileWidget
|
||||
default_validators = [
|
||||
FileExtensionValidator(['jpg', 'jpeg', 'png']),
|
||||
MaxFilesizeValidator(MAX_UPLOAD_SIZE),
|
||||
]
|
||||
|
||||
def widget_attrs(self, widget):
|
||||
attrs = super().widget_attrs(widget)
|
||||
if isinstance(widget, FileInput) and 'accept' not in widget.attrs:
|
||||
attrs.setdefault('accept', 'image/png,image/jpeg') # image/*
|
||||
if isinstance(widget, ImageFileWidget):
|
||||
attrs.update({
|
||||
'data-upload-limit': readableToInt(MAX_UPLOAD_SIZE),
|
||||
'data-upload-limit-str': MAX_UPLOAD_SIZE,
|
||||
'onchange': 'validate_upload_limit(this)',
|
||||
})
|
||||
return attrs
|
||||
|
||||
|
||||
class FileWithImagePreview(models.FileField): # use ImageField to omit Pillow
|
||||
__del_image_on_save = False
|
||||
|
||||
def formfield(self, **kwargs):
|
||||
if kwargs['widget'] is AdminFileWidget:
|
||||
# Override admin widget. Defined by ImgField anyway
|
||||
del kwargs['widget']
|
||||
return super().formfield(**{'form_class': ImgField, **kwargs})
|
||||
|
||||
def save_form_data(self, instance, data):
|
||||
if data is False:
|
||||
self.__del_image_on_save = True
|
||||
super().save_form_data(instance, data)
|
||||
|
||||
def pre_save(self, model_instance, add):
|
||||
if self.__del_image_on_save:
|
||||
self.__del_image_on_save = False
|
||||
self.deletePreviousImage(model_instance)
|
||||
return super().pre_save(model_instance, add)
|
||||
|
||||
def deletePreviousImage(self, instance: models.Model):
|
||||
if not instance.pk:
|
||||
return
|
||||
prev = instance.__class__.objects.get(pk=instance.pk)
|
||||
imgField = getattr(prev, self.attname)
|
||||
imgField.delete(save=False)
|
||||
BIN
backend/common/locale/de/LC_MESSAGES/django.mo
Normal file
BIN
backend/common/locale/de/LC_MESSAGES/django.mo
Normal file
Binary file not shown.
8
backend/common/locale/de/LC_MESSAGES/django.po
Normal file
8
backend/common/locale/de/LC_MESSAGES/django.po
Normal file
@@ -0,0 +1,8 @@
|
||||
msgid ""
|
||||
msgstr ""
|
||||
"Content-Type: text/plain; charset=UTF-8\n"
|
||||
"Content-Transfer-Encoding: 8bit\n"
|
||||
"Language: de\n"
|
||||
|
||||
msgid "File size too large (max. %(limit_value)s)."
|
||||
msgstr "Datei zu groß (max. %(limit_value)s)."
|
||||
30
backend/common/settings.py
Normal file
30
backend/common/settings.py
Normal file
@@ -0,0 +1,30 @@
|
||||
|
||||
TINYMCE_DEFAULT_CONFIG = {
|
||||
"width": "100%",
|
||||
|
||||
# see https://www.tiny.cloud/docs/tinymce/latest/available-menu-items/
|
||||
"menubar": "edit view insert format table help", # file tools
|
||||
|
||||
"plugins": "advlist autolink lists link image charmap anchor "
|
||||
"searchreplace visualblocks code fullscreen insertdatetime media table "
|
||||
"help", # paste print preview wordcount
|
||||
|
||||
# see https://www.tiny.cloud/docs/tinymce/latest/available-toolbar-buttons/
|
||||
"toolbar": "undo redo | blocks | bold italic removeformat | "
|
||||
"bullist numlist outdent indent",
|
||||
# forecolor backcolor | alignleft aligncenter alignright alignjustify
|
||||
|
||||
"promotion": False, # hide upgrade button
|
||||
"language": "de_DE",
|
||||
# "custom_undo_redo_levels": 10,
|
||||
|
||||
"images_file_types": 'jpeg,jpg,png,gif',
|
||||
"images_upload_handler": "tinymce_image_upload_handler",
|
||||
"images_reuse_filename": True, # prevent image edits from reuploading imgs
|
||||
"convert_urls": False,
|
||||
}
|
||||
|
||||
TINYMCE_EXTRA_MEDIA = {
|
||||
'css': {'all': []},
|
||||
'js': ['admin/tinymce-upload.js'],
|
||||
}
|
||||
6
backend/common/static/admin/file-upload-validator.js
Normal file
6
backend/common/static/admin/file-upload-validator.js
Normal file
@@ -0,0 +1,6 @@
|
||||
function validate_upload_limit(sender) {
|
||||
if (sender.files[0].size > sender.dataset.uploadLimit) {
|
||||
sender.value = '';
|
||||
alert(`Datei zu groß (max. ${sender.dataset.uploadLimitStr})`);
|
||||
}
|
||||
}
|
||||
55
backend/common/static/admin/tinymce-upload.js
Normal file
55
backend/common/static/admin/tinymce-upload.js
Normal file
@@ -0,0 +1,55 @@
|
||||
function tinymce_image_upload_handler(blobInfo, progress) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const match = self.location.pathname.match('/app/place/([0-9]*)/');
|
||||
if (!match) {
|
||||
return reject('Cannot match place id from URL.');
|
||||
}
|
||||
|
||||
// FIXME: this will still upload the image as base64 string
|
||||
// if (blobInfo.blob().size > 1_000_000) { // >1MB
|
||||
// return reject('Image too large. Max file size: 1 MB');
|
||||
// }
|
||||
|
||||
const placeId = match[1];
|
||||
let xhr, formData;
|
||||
// token = Cookies.get("csrftoken");
|
||||
token = document.cookie.match('csrftoken=([^;]*)')[1];
|
||||
xhr = new XMLHttpRequest();
|
||||
xhr.withCredentials = false;
|
||||
xhr.open('POST', '/tinymce/upload/' + placeId + '/');
|
||||
xhr.setRequestHeader('X-CSRFToken', token);
|
||||
|
||||
if (progress) {
|
||||
xhr.upload.onprogress = function (e) {
|
||||
progress(e.loaded / e.total * 100);
|
||||
};
|
||||
}
|
||||
xhr.onload = function () {
|
||||
let json;
|
||||
|
||||
if (xhr.status === 403) {
|
||||
return reject('HTTP Error: ' + xhr.status, { remove: true });
|
||||
}
|
||||
|
||||
if (xhr.status < 200 || xhr.status >= 300) {
|
||||
return reject('HTTP Error: ' + xhr.status);
|
||||
}
|
||||
|
||||
json = JSON.parse(xhr.responseText);
|
||||
|
||||
if (!json || typeof json.location != 'string') {
|
||||
return reject('Invalid JSON: ' + xhr.responseText);
|
||||
}
|
||||
|
||||
return resolve(json.location);
|
||||
};
|
||||
xhr.onerror = function () {
|
||||
return reject('Image upload failed due to a XHR Transport error. Code: ' + xhr.status);
|
||||
};
|
||||
|
||||
formData = new FormData();
|
||||
formData.append('file', blobInfo.blob(), blobInfo.filename());
|
||||
|
||||
xhr.send(formData);
|
||||
});
|
||||
}
|
||||
BIN
backend/common/static/favicon.ico
Normal file
BIN
backend/common/static/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 905 B |
17
backend/common/templates/forms/audio-file.html
Normal file
17
backend/common/templates/forms/audio-file.html
Normal file
@@ -0,0 +1,17 @@
|
||||
<div style="width: 100%">
|
||||
{% if widget.is_initial %}
|
||||
<audio controls preload="none" style="width: 100%">
|
||||
<source src="{{MEDIA_URL}}{{widget.value}}" type="audio/mpeg">
|
||||
Browser does not support Audio
|
||||
</audio>
|
||||
{% if not widget.required %}
|
||||
<span class="clearable-file-input">
|
||||
<input type="checkbox" name="{{ widget.checkbox_name }}" id="{{ widget.checkbox_id }}"{% if widget.attrs.disabled %} disabled{% endif %}>
|
||||
<label for="{{ widget.checkbox_id }}">{{ widget.clear_checkbox_label }}</label>
|
||||
</span>
|
||||
{% endif %}
|
||||
<br>
|
||||
<span>{{ widget.input_text }}:</span>
|
||||
{% endif %}
|
||||
<input type="{{ widget.type }}" name="{{ widget.name }}"{% include "django/forms/widgets/attrs.html" %}>
|
||||
</div>
|
||||
14
backend/common/templates/forms/img-with-preview.html
Normal file
14
backend/common/templates/forms/img-with-preview.html
Normal file
@@ -0,0 +1,14 @@
|
||||
<div>
|
||||
{% if widget.is_initial %}
|
||||
<img src="{{MEDIA_URL}}{{widget.value}}" style="max-width: 150px; max-height: 150px; margin: 8px;" />
|
||||
{% if not widget.required %}
|
||||
<span class="clearable-file-input">
|
||||
<input type="checkbox" name="{{ widget.checkbox_name }}" id="{{ widget.checkbox_id }}"{% if widget.attrs.disabled %} disabled{% endif %}>
|
||||
<label for="{{ widget.checkbox_id }}">{{ widget.clear_checkbox_label }}</label>
|
||||
</span>
|
||||
{% endif %}
|
||||
<br>
|
||||
<span>{{ widget.input_text }}:</span>
|
||||
{% endif %}
|
||||
<input type="{{ widget.type }}" name="{{ widget.name }}"{% include "django/forms/widgets/attrs.html" %}>
|
||||
</div>
|
||||
36
backend/common/urls.py
Normal file
36
backend/common/urls.py
Normal file
@@ -0,0 +1,36 @@
|
||||
from django.conf import settings
|
||||
from django.http import HttpRequest, JsonResponse
|
||||
from django.urls import include, path
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from app.models.place import Place
|
||||
|
||||
|
||||
def tinymce_upload(request: HttpRequest, placeId: int):
|
||||
if request.method != 'POST':
|
||||
return JsonResponse({'error': 'unsupported method type'})
|
||||
|
||||
try:
|
||||
Place.objects.get(pk=placeId)
|
||||
except Place.DoesNotExist:
|
||||
return JsonResponse({'error': 'place does not exist'})
|
||||
|
||||
file = request.FILES.get('file')
|
||||
if not file:
|
||||
return JsonResponse({'error': 'could not read file'})
|
||||
|
||||
save_dir = Path(settings.MEDIA_ROOT) / str(placeId)
|
||||
if not save_dir.exists():
|
||||
save_dir.mkdir()
|
||||
with open(save_dir / file.name, 'wb') as fp:
|
||||
fp.write(file.read())
|
||||
|
||||
fname = f'{placeId}/{file.name}'
|
||||
return JsonResponse({'location': settings.MEDIA_URL + fname})
|
||||
|
||||
|
||||
urlpatterns = [
|
||||
path('tinymce/', include('tinymce.urls')),
|
||||
path('tinymce/upload/<int:placeId>/', tinymce_upload),
|
||||
]
|
||||
23
backend/common/validators.py
Normal file
23
backend/common/validators.py
Normal file
@@ -0,0 +1,23 @@
|
||||
from django.core.validators import BaseValidator
|
||||
from django.utils.deconstruct import deconstructible
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from django.core.files.uploadedfile import TemporaryUploadedFile
|
||||
|
||||
|
||||
UNITS = {'k': 1000, 'm': 1000_000, 'g': 1000_000_000}
|
||||
|
||||
|
||||
def readableToInt(limit: str) -> int:
|
||||
x = limit.lower().rstrip(' ib') # KiB & KB -> k
|
||||
multiply = UNITS.get(x[-1], 1)
|
||||
value = float(x.rstrip(' _kmg').replace(',', '.'))
|
||||
return int(value * multiply)
|
||||
|
||||
|
||||
@deconstructible
|
||||
class MaxFilesizeValidator(BaseValidator):
|
||||
message = _('File size too large (max. %(limit_value)s).')
|
||||
code = 'max_filesize'
|
||||
|
||||
def compare(self, a: TemporaryUploadedFile, limit: str):
|
||||
return a.size > readableToInt(limit)
|
||||
0
backend/config/__init__.py
Normal file
0
backend/config/__init__.py
Normal file
16
backend/config/asgi.py
Normal file
16
backend/config/asgi.py
Normal file
@@ -0,0 +1,16 @@
|
||||
"""
|
||||
ASGI config for 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.2/howto/deployment/asgi/
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from django.core.asgi import get_asgi_application
|
||||
|
||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
|
||||
|
||||
application = get_asgi_application()
|
||||
151
backend/config/settings.py
Normal file
151
backend/config/settings.py
Normal file
@@ -0,0 +1,151 @@
|
||||
"""
|
||||
Django settings for project.
|
||||
|
||||
Generated by 'django-admin startproject' using Django 4.2.13.
|
||||
|
||||
For more information on this file, see
|
||||
https://docs.djangoproject.com/en/4.2/topics/settings/
|
||||
|
||||
For the full list of settings and their values, see
|
||||
https://docs.djangoproject.com/en/4.2/ref/settings/
|
||||
"""
|
||||
import os
|
||||
from pathlib import Path
|
||||
from common.settings import * # noqa: 401
|
||||
|
||||
# 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.2/howto/deployment/checklist/
|
||||
|
||||
# SECURITY WARNING: keep the secret key used in production secret!
|
||||
SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', 'insecure-$a^nh$d!tgut43^91@')
|
||||
|
||||
# SECURITY WARNING: don't run with debug turned on in production!
|
||||
DEBUG = SECRET_KEY.startswith('insecure') or \
|
||||
os.environ.get('DEBUG', '0').lower() not in ['false', 'no', '0']
|
||||
|
||||
ALLOWED_HOSTS = []
|
||||
ALLOWED_HOSTS.extend(
|
||||
filter(
|
||||
None,
|
||||
os.environ.get('ALLOWED_HOSTS', '*').split(','),
|
||||
)
|
||||
)
|
||||
CSRF_TRUSTED_ORIGINS = ['https://' + x for x in ALLOWED_HOSTS]
|
||||
|
||||
|
||||
# Application definition
|
||||
|
||||
INSTALLED_APPS = [
|
||||
'django.contrib.admin',
|
||||
'django.contrib.auth',
|
||||
'django.contrib.contenttypes',
|
||||
'django.contrib.sessions',
|
||||
'django.contrib.messages',
|
||||
'django.contrib.staticfiles',
|
||||
'colorfield',
|
||||
'tinymce',
|
||||
'map_location',
|
||||
'common',
|
||||
'app',
|
||||
]
|
||||
|
||||
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',
|
||||
]
|
||||
|
||||
ROOT_URLCONF = 'config.urls'
|
||||
|
||||
TEMPLATES = [
|
||||
{
|
||||
'BACKEND': 'django.template.backends.django.DjangoTemplates',
|
||||
'DIRS': [], # BASE_DIR / 'templates'
|
||||
'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 = 'config.wsgi.application'
|
||||
|
||||
|
||||
# Database
|
||||
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases
|
||||
|
||||
DATABASES = {
|
||||
'default': {
|
||||
'ENGINE': 'django.db.backends.sqlite3',
|
||||
'NAME': BASE_DIR / 'db' / 'db.sqlite3',
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
# Password validation
|
||||
# https://docs.djangoproject.com/en/4.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/4.2/topics/i18n/
|
||||
|
||||
LANGUAGE_CODE = 'de'
|
||||
|
||||
TIME_ZONE = 'Europe/Berlin'
|
||||
|
||||
USE_I18N = True
|
||||
|
||||
USE_TZ = False
|
||||
|
||||
|
||||
# Static files (CSS, JavaScript, Images)
|
||||
# https://docs.djangoproject.com/en/4.2/howto/static-files/
|
||||
|
||||
STATIC_URL = 'static/'
|
||||
|
||||
# Default primary key field type
|
||||
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field
|
||||
|
||||
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
|
||||
|
||||
|
||||
# Custom
|
||||
|
||||
ADMIN_URL = os.environ.get('ADMIN_URL', 'admin/').rstrip('/') + '/'
|
||||
|
||||
STATIC_ROOT = BASE_DIR / 'static'
|
||||
|
||||
MEDIA_URL = 'data/'
|
||||
MEDIA_ROOT = BASE_DIR / 'data'
|
||||
|
||||
STATIC_ROOT.mkdir(exist_ok=True)
|
||||
MEDIA_ROOT.mkdir(exist_ok=True)
|
||||
(BASE_DIR / 'db').mkdir(exist_ok=True)
|
||||
26
backend/config/urls.py
Normal file
26
backend/config/urls.py
Normal file
@@ -0,0 +1,26 @@
|
||||
"""
|
||||
URL configuration for project.
|
||||
|
||||
The `urlpatterns` list routes URLs to views. For more information please see:
|
||||
https://docs.djangoproject.com/en/4.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.conf import settings
|
||||
from django.conf.urls.static import static
|
||||
from django.contrib import admin
|
||||
from django.urls import include, path
|
||||
|
||||
|
||||
urlpatterns = [
|
||||
path(settings.ADMIN_URL, admin.site.urls),
|
||||
path('', include('common.urls')),
|
||||
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
|
||||
16
backend/config/wsgi.py
Normal file
16
backend/config/wsgi.py
Normal file
@@ -0,0 +1,16 @@
|
||||
"""
|
||||
WSGI config for 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/4.2/howto/deployment/wsgi/
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from django.core.wsgi import get_wsgi_application
|
||||
|
||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
|
||||
|
||||
application = get_wsgi_application()
|
||||
30
backend/docker-compose.yml
Executable file
30
backend/docker-compose.yml
Executable file
@@ -0,0 +1,30 @@
|
||||
services:
|
||||
app:
|
||||
container_name: klangkarte
|
||||
build:
|
||||
context: .
|
||||
# dockerfile: .
|
||||
pull_policy: build
|
||||
ports:
|
||||
- 127.0.0.1:8070:8000
|
||||
image: klangkarte:latest
|
||||
working_dir: /django_project
|
||||
environment:
|
||||
DJANGO_SECRET_KEY: ${DJANGO_SECRET_KEY}
|
||||
ALLOWED_HOSTS: ${ALLOWED_HOSTS}
|
||||
DEBUG: ${DEBUG:-0}
|
||||
volumes:
|
||||
- volume-klangkarte:/django_project/db
|
||||
- /srv/http/klangkarte-data:/django_project/data
|
||||
- /srv/http/klangkarte-static:/django_project/static
|
||||
restart: unless-stopped
|
||||
networks:
|
||||
- network-klangkarte
|
||||
|
||||
volumes:
|
||||
volume-klangkarte:
|
||||
name: klangkarte
|
||||
|
||||
networks:
|
||||
network-klangkarte:
|
||||
name: klangkarte
|
||||
22
backend/manage.py
Executable file
22
backend/manage.py
Executable 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', 'config.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()
|
||||
5
backend/requirements.txt
Normal file
5
backend/requirements.txt
Normal file
@@ -0,0 +1,5 @@
|
||||
Django==4.2.13
|
||||
Pillow==10.3.0
|
||||
django_colorfield==0.11.0
|
||||
django-tinymce==4.0.0
|
||||
django-map-location==0.9.1
|
||||
6
backend/scripts/run.sh
Executable file
6
backend/scripts/run.sh
Executable file
@@ -0,0 +1,6 @@
|
||||
#!/bin/sh
|
||||
python manage.py collectstatic --noinput
|
||||
python manage.py migrate
|
||||
|
||||
# python -m uvicorn --port 8000 config.asgi:application
|
||||
python -m gunicorn -b 0.0.0.0:8000 -k uvicorn.workers.UvicornWorker config.asgi:application
|
||||
Reference in New Issue
Block a user