Update admin & upload template

This commit is contained in:
Nyymix 2025-03-19 21:24:32 +02:00
parent dfd4f8a4e0
commit e4816681bd
2 changed files with 156 additions and 93 deletions

View file

@ -11,6 +11,7 @@ from imagekit.processors import ResizeToFit
from gallery.models import Album, City, Location, Photo, Redir
# Thumbnail-luokka admin-näkymää varten
class AdminThumbnailSpec(ImageSpec):
processors = [ResizeToFit(100, 100)]
format = 'JPEG'
@ -18,6 +19,7 @@ class AdminThumbnailSpec(ImageSpec):
def cached_admin_thumb(instance):
"""Palauttaa cachetetun thumbnailin, jos kuva on olemassa."""
if instance.photo:
cached = ImageCacheFile(AdminThumbnailSpec(instance.photo))
cached.generate()
@ -25,6 +27,7 @@ def cached_admin_thumb(instance):
return None
# 🔹 RedirAdmin uudelleenohjausten hallinta
class RedirAdmin(admin.ModelAdmin):
list_display = ('path', 'album', 'test_url')
search_fields = ('path',)
@ -33,18 +36,21 @@ class RedirAdmin(admin.ModelAdmin):
list_editable = ('album',)
def formfield_for_foreignkey(self, db_field, request, **kwargs):
"""Järjestää albumivalikon aakkosjärjestykseen."""
if db_field.name == "album":
kwargs["queryset"] = Album.objects.all().order_by('name')
return super().formfield_for_foreignkey(db_field, request, **kwargs)
def test_url(self, obj):
"""Luo linkin, jolla voi testata uudelleenohjauksen."""
return format_html(
'<a href="/{}" target="_blank">http://nyymix.net/{}</a>',
obj.path, obj.path
)
test_url.short_description = "Test redirection"
test_url.short_description = "Test Redirection"
# 🔹 CityAdmin kaupunkien hallinta
class CityAdmin(admin.ModelAdmin):
list_display = ('name',)
search_fields = ('name',)
@ -52,6 +58,7 @@ class CityAdmin(admin.ModelAdmin):
list_per_page = 30
# 🔹 LocationAdmin sijaintien hallinta
class LocationAdmin(admin.ModelAdmin):
list_display = ('city', 'place')
list_filter = ('city',)
@ -60,6 +67,7 @@ class LocationAdmin(admin.ModelAdmin):
list_per_page = 30
# 🔹 AlbumAdmin albumien hallinta
class AlbumAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('name',)}
list_display = ('name', 'location', 'album_date', 'is_public', 'upload_link', 'thumbnail')
@ -68,10 +76,10 @@ class AlbumAdmin(admin.ModelAdmin):
list_per_page = 20
list_editable = ('is_public',)
readonly_fields = ['cover_preview']
change_form_template = "admin/gallery/album/change_form.html"
def get_urls(self):
"""Lisää mukautetun URL-reitin valokuvien lataamiselle."""
urls = super().get_urls()
custom_urls = [
path('<int:album_id>/upload/', self.admin_site.admin_view(self.upload_photos), name="gallery_album_upload"),
@ -84,14 +92,16 @@ class AlbumAdmin(admin.ModelAdmin):
if request.method == 'POST' and request.FILES:
uploaded_files = request.FILES.getlist('photo')
for file in uploaded_files:
Photo.objects.create(album=album, photo=file)
if not uploaded_files:
return JsonResponse({"error": "No files uploaded."}, status=400)
Photo.objects.bulk_create([Photo(album=album, photo=file) for file in uploaded_files])
return JsonResponse({"message": "Photos uploaded successfully!"})
return render(request, 'admin/upload_photos.html', {'album': album})
def upload_link(self, obj):
"""Lisää 'Upload Photos' -painikkeen albumin muokkaussivulle"""
"""Lisää 'Upload Photos' -painikkeen albumin muokkaussivulle."""
if obj.id:
url = reverse("admin:gallery_album_upload", kwargs={"album_id": obj.id})
return format_html('<a href="{}" class="button">Upload Photos</a>', url)
@ -99,24 +109,27 @@ class AlbumAdmin(admin.ModelAdmin):
upload_link.short_description = "Upload Photos"
def thumbnail(self, obj):
"""Näyttää albumin kansikuvan pikkukuvan."""
if obj.cover and obj.cover.photo:
return format_html(
'<img src="{}" style="width: 50px; height: auto;"/>',
obj.cover.photo.url,
obj.cover.photo_sm.url,
)
return "-"
thumbnail.short_description = "Thumbnail"
def cover_preview(self, obj):
"""Näyttää albumin kansikuvan suurempana esikatseluna."""
if obj.cover and obj.cover.photo:
return format_html(
'<img src="{}" style="max-width: 300px; height: auto;"/>',
obj.cover.photo.url,
obj.cover.photo_sm.url,
)
return "No cover image available"
cover_preview.short_description = "Cover Preview"
def formfield_for_foreignkey(self, db_field, request, **kwargs):
"""Rajoittaa kansikuvan valintaa vain albumin omiin kuviin."""
if db_field.name == "cover":
if hasattr(request, 'resolver_match') and request.resolver_match.kwargs.get('object_id'):
album_id = request.resolver_match.kwargs['object_id']
@ -125,6 +138,7 @@ class AlbumAdmin(admin.ModelAdmin):
return super().formfield_for_foreignkey(db_field, request, **kwargs)
# 🔹 PhotoAdmin kuvien hallinta
class PhotoAdmin(admin.ModelAdmin):
list_display = ('slug', 'album', 'is_favorite', 'admin_thumbnail')
list_display_links = ('slug',)
@ -136,6 +150,7 @@ class PhotoAdmin(admin.ModelAdmin):
list_editable = ('is_favorite',)
# 🔹 Rekisteröidään admin-paneeliin
admin.site.register(City, CityAdmin)
admin.site.register(Location, LocationAdmin)
admin.site.register(Album, AlbumAdmin)

View file

@ -1,46 +1,89 @@
{% extends "admin/base_site.html" %}
{% block content %}
<div class="container mt-3">
<h1>Upload Photos to {{ album.name }}</h1>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/uikit/dist/css/uikit.min.css" />
<script src="https://cdn.jsdelivr.net/npm/uikit/dist/js/uikit.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/uikit/dist/js/uikit-icons.min.js"></script>
<div class="module">
<h2>Upload Photos to {{ album.name }}</h2>
<form id="upload-form" method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="uk-margin">
<div id="js-drop" class="uk-placeholder uk-text-center uk-margin-medium-top">
<span uk-icon="icon: cloud-upload"></span>
<span class="uk-text-middle">Drag files here or</span>
<div uk-form-custom>
<div class="form-row">
<div id="js-drop" class="drop-area">
<p><strong>Drag files here</strong> or click below to select</p>
<input id="file-input" type="file" name="photo" multiple accept=".jpg,.jpeg">
<span class="uk-link">select them</span>
</div>
</div>
<ul id="file-list" class="uk-list uk-list-divider"></ul>
<ul id="file-list" class="messagelist"></ul>
<p>Total size: <span id="total-size">0</span> MB</p>
<progress id="js-progressbar" class="uk-progress" value="0" max="100" hidden></progress>
</div>
<button id="upload-button" class="uk-button uk-button-primary" type="button">Upload</button>
<progress id="js-progressbar" max="100" value="0" hidden></progress>
<div class="submit-row">
<button id="upload-button" class="default" type="button">Upload</button>
</div>
</form>
</div>
<style>
.drop-area {
border: 2px dashed #ddd;
padding: 20px;
text-align: center;
background: #f9f9f9;
cursor: pointer;
margin-bottom: 10px;
transition: background 0.3s, border-color 0.3s;
}
.drop-area.dragover {
border-color: #007bff;
background: #eef7ff;
}
#file-list {
margin-top: 10px;
list-style: none;
padding: 0;
}
#file-list li {
background: #f5f5f5;
padding: 5px;
margin-bottom: 5px;
border-radius: 3px;
}
.success {
color: green;
}
.error {
color: red;
}
</style>
<script>
document.addEventListener("DOMContentLoaded", function () {
const fileInput = document.getElementById('file-input');
const fileList = document.getElementById('file-list');
const totalSizeElement = document.getElementById('total-size');
const uploadButton = document.getElementById('upload-button');
const progressBar = document.getElementById('js-progressbar');
const dropArea = document.getElementById('js-drop');
let filesToUpload = [];
let totalSize = 0;
const maxSize = 10 * 1024 * 1024; // 10MB per file
function updateFileList(newFiles) {
filesToUpload = [...newFiles].filter(file => file.name.match(/\.jpe?g$/i));
// Suodatetaan vain JPEG-tiedostot ja poistetaan liian suuret
filesToUpload = [...newFiles].filter(file => {
if (!file.name.match(/\.jpe?g$/i)) {
alert(`File ${file.name} is not a JPG!`);
return false;
}
if (file.size > maxSize) {
alert(`File ${file.name} is too large! Max size: 10MB.`);
return false;
}
return true;
});
fileList.innerHTML = '';
totalSize = filesToUpload.reduce((acc, file) => acc + file.size, 0);
@ -49,6 +92,7 @@
listItem.textContent = `${file.name} (${(file.size / (1024 * 1024)).toFixed(2)} MB)`;
fileList.appendChild(listItem);
});
totalSizeElement.textContent = (totalSize / (1024 * 1024)).toFixed(2);
}
@ -56,12 +100,12 @@
['dragenter', 'dragover'].forEach(eventName => dropArea.addEventListener(eventName, e => {
e.preventDefault();
dropArea.classList.add('uk-active');
dropArea.classList.add('dragover');
}));
['dragleave', 'drop'].forEach(eventName => dropArea.addEventListener(eventName, e => {
e.preventDefault();
dropArea.classList.remove('uk-active');
dropArea.classList.remove('dragover');
}));
dropArea.addEventListener('drop', event => {
@ -75,18 +119,20 @@
}
progressBar.hidden = false;
let uploaded = 0;
progressBar.value = 0;
let uploadedSize = 0;
filesToUpload.forEach((file, index) => {
const xhr = new XMLHttpRequest();
const formData = new FormData();
formData.append('photo', file);
formData.append('csrfmiddlewaretoken', '{{ csrf_token }}');
xhr.open('POST', '', true);
xhr.upload.onprogress = event => {
if (event.lengthComputable) {
progressBar.value = ((uploaded + event.loaded) / totalSize) * 100;
progressBar.value = ((uploadedSize + event.loaded) / totalSize) * 100;
}
};
@ -94,21 +140,23 @@
const listItem = fileList.children[index];
if (xhr.status === 200) {
listItem.textContent += ' - Upload successful!';
listItem.classList.add('uk-text-success');
listItem.classList.add('success');
} else {
listItem.textContent += ' - Upload failed!';
listItem.classList.add('uk-text-danger');
listItem.classList.add('error');
}
uploaded += file.size;
uploadedSize += file.size;
};
xhr.onerror = () => {
fileList.children[index].textContent += ' - Upload failed!';
fileList.children[index].classList.add('uk-text-danger');
const listItem = fileList.children[index];
listItem.textContent += ' - Upload failed!';
listItem.classList.add('error');
};
xhr.send(formData);
});
});
});
</script>
{% endblock %}