Update admin & upload template
This commit is contained in:
parent
dfd4f8a4e0
commit
e4816681bd
2 changed files with 156 additions and 93 deletions
|
@ -11,6 +11,7 @@ from imagekit.processors import ResizeToFit
|
||||||
from gallery.models import Album, City, Location, Photo, Redir
|
from gallery.models import Album, City, Location, Photo, Redir
|
||||||
|
|
||||||
|
|
||||||
|
# Thumbnail-luokka admin-näkymää varten
|
||||||
class AdminThumbnailSpec(ImageSpec):
|
class AdminThumbnailSpec(ImageSpec):
|
||||||
processors = [ResizeToFit(100, 100)]
|
processors = [ResizeToFit(100, 100)]
|
||||||
format = 'JPEG'
|
format = 'JPEG'
|
||||||
|
@ -18,6 +19,7 @@ class AdminThumbnailSpec(ImageSpec):
|
||||||
|
|
||||||
|
|
||||||
def cached_admin_thumb(instance):
|
def cached_admin_thumb(instance):
|
||||||
|
"""Palauttaa cachetetun thumbnailin, jos kuva on olemassa."""
|
||||||
if instance.photo:
|
if instance.photo:
|
||||||
cached = ImageCacheFile(AdminThumbnailSpec(instance.photo))
|
cached = ImageCacheFile(AdminThumbnailSpec(instance.photo))
|
||||||
cached.generate()
|
cached.generate()
|
||||||
|
@ -25,6 +27,7 @@ def cached_admin_thumb(instance):
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
# 🔹 RedirAdmin – uudelleenohjausten hallinta
|
||||||
class RedirAdmin(admin.ModelAdmin):
|
class RedirAdmin(admin.ModelAdmin):
|
||||||
list_display = ('path', 'album', 'test_url')
|
list_display = ('path', 'album', 'test_url')
|
||||||
search_fields = ('path',)
|
search_fields = ('path',)
|
||||||
|
@ -33,18 +36,21 @@ class RedirAdmin(admin.ModelAdmin):
|
||||||
list_editable = ('album',)
|
list_editable = ('album',)
|
||||||
|
|
||||||
def formfield_for_foreignkey(self, db_field, request, **kwargs):
|
def formfield_for_foreignkey(self, db_field, request, **kwargs):
|
||||||
|
"""Järjestää albumivalikon aakkosjärjestykseen."""
|
||||||
if db_field.name == "album":
|
if db_field.name == "album":
|
||||||
kwargs["queryset"] = Album.objects.all().order_by('name')
|
kwargs["queryset"] = Album.objects.all().order_by('name')
|
||||||
return super().formfield_for_foreignkey(db_field, request, **kwargs)
|
return super().formfield_for_foreignkey(db_field, request, **kwargs)
|
||||||
|
|
||||||
def test_url(self, obj):
|
def test_url(self, obj):
|
||||||
|
"""Luo linkin, jolla voi testata uudelleenohjauksen."""
|
||||||
return format_html(
|
return format_html(
|
||||||
'<a href="/{}" target="_blank">http://nyymix.net/{}</a>',
|
'<a href="/{}" target="_blank">http://nyymix.net/{}</a>',
|
||||||
obj.path, obj.path
|
obj.path, obj.path
|
||||||
)
|
)
|
||||||
test_url.short_description = "Test redirection"
|
test_url.short_description = "Test Redirection"
|
||||||
|
|
||||||
|
|
||||||
|
# 🔹 CityAdmin – kaupunkien hallinta
|
||||||
class CityAdmin(admin.ModelAdmin):
|
class CityAdmin(admin.ModelAdmin):
|
||||||
list_display = ('name',)
|
list_display = ('name',)
|
||||||
search_fields = ('name',)
|
search_fields = ('name',)
|
||||||
|
@ -52,6 +58,7 @@ class CityAdmin(admin.ModelAdmin):
|
||||||
list_per_page = 30
|
list_per_page = 30
|
||||||
|
|
||||||
|
|
||||||
|
# 🔹 LocationAdmin – sijaintien hallinta
|
||||||
class LocationAdmin(admin.ModelAdmin):
|
class LocationAdmin(admin.ModelAdmin):
|
||||||
list_display = ('city', 'place')
|
list_display = ('city', 'place')
|
||||||
list_filter = ('city',)
|
list_filter = ('city',)
|
||||||
|
@ -60,6 +67,7 @@ class LocationAdmin(admin.ModelAdmin):
|
||||||
list_per_page = 30
|
list_per_page = 30
|
||||||
|
|
||||||
|
|
||||||
|
# 🔹 AlbumAdmin – albumien hallinta
|
||||||
class AlbumAdmin(admin.ModelAdmin):
|
class AlbumAdmin(admin.ModelAdmin):
|
||||||
prepopulated_fields = {'slug': ('name',)}
|
prepopulated_fields = {'slug': ('name',)}
|
||||||
list_display = ('name', 'location', 'album_date', 'is_public', 'upload_link', 'thumbnail')
|
list_display = ('name', 'location', 'album_date', 'is_public', 'upload_link', 'thumbnail')
|
||||||
|
@ -68,10 +76,10 @@ class AlbumAdmin(admin.ModelAdmin):
|
||||||
list_per_page = 20
|
list_per_page = 20
|
||||||
list_editable = ('is_public',)
|
list_editable = ('is_public',)
|
||||||
readonly_fields = ['cover_preview']
|
readonly_fields = ['cover_preview']
|
||||||
|
|
||||||
change_form_template = "admin/gallery/album/change_form.html"
|
change_form_template = "admin/gallery/album/change_form.html"
|
||||||
|
|
||||||
def get_urls(self):
|
def get_urls(self):
|
||||||
|
"""Lisää mukautetun URL-reitin valokuvien lataamiselle."""
|
||||||
urls = super().get_urls()
|
urls = super().get_urls()
|
||||||
custom_urls = [
|
custom_urls = [
|
||||||
path('<int:album_id>/upload/', self.admin_site.admin_view(self.upload_photos), name="gallery_album_upload"),
|
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:
|
if request.method == 'POST' and request.FILES:
|
||||||
uploaded_files = request.FILES.getlist('photo')
|
uploaded_files = request.FILES.getlist('photo')
|
||||||
for file in uploaded_files:
|
if not uploaded_files:
|
||||||
Photo.objects.create(album=album, photo=file)
|
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 JsonResponse({"message": "Photos uploaded successfully!"})
|
||||||
|
|
||||||
return render(request, 'admin/upload_photos.html', {'album': album})
|
return render(request, 'admin/upload_photos.html', {'album': album})
|
||||||
|
|
||||||
def upload_link(self, obj):
|
def upload_link(self, obj):
|
||||||
"""Lisää 'Upload Photos' -painikkeen albumin muokkaussivulle"""
|
"""Lisää 'Upload Photos' -painikkeen albumin muokkaussivulle."""
|
||||||
if obj.id:
|
if obj.id:
|
||||||
url = reverse("admin:gallery_album_upload", kwargs={"album_id": obj.id})
|
url = reverse("admin:gallery_album_upload", kwargs={"album_id": obj.id})
|
||||||
return format_html('<a href="{}" class="button">Upload Photos</a>', url)
|
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"
|
upload_link.short_description = "Upload Photos"
|
||||||
|
|
||||||
def thumbnail(self, obj):
|
def thumbnail(self, obj):
|
||||||
|
"""Näyttää albumin kansikuvan pikkukuvan."""
|
||||||
if obj.cover and obj.cover.photo:
|
if obj.cover and obj.cover.photo:
|
||||||
return format_html(
|
return format_html(
|
||||||
'<img src="{}" style="width: 50px; height: auto;"/>',
|
'<img src="{}" style="width: 50px; height: auto;"/>',
|
||||||
obj.cover.photo.url,
|
obj.cover.photo_sm.url,
|
||||||
)
|
)
|
||||||
return "-"
|
return "-"
|
||||||
thumbnail.short_description = "Thumbnail"
|
thumbnail.short_description = "Thumbnail"
|
||||||
|
|
||||||
def cover_preview(self, obj):
|
def cover_preview(self, obj):
|
||||||
|
"""Näyttää albumin kansikuvan suurempana esikatseluna."""
|
||||||
if obj.cover and obj.cover.photo:
|
if obj.cover and obj.cover.photo:
|
||||||
return format_html(
|
return format_html(
|
||||||
'<img src="{}" style="max-width: 300px; height: auto;"/>',
|
'<img src="{}" style="max-width: 300px; height: auto;"/>',
|
||||||
obj.cover.photo.url,
|
obj.cover.photo_sm.url,
|
||||||
)
|
)
|
||||||
return "No cover image available"
|
return "No cover image available"
|
||||||
cover_preview.short_description = "Cover Preview"
|
cover_preview.short_description = "Cover Preview"
|
||||||
|
|
||||||
def formfield_for_foreignkey(self, db_field, request, **kwargs):
|
def formfield_for_foreignkey(self, db_field, request, **kwargs):
|
||||||
|
"""Rajoittaa kansikuvan valintaa vain albumin omiin kuviin."""
|
||||||
if db_field.name == "cover":
|
if db_field.name == "cover":
|
||||||
if hasattr(request, 'resolver_match') and request.resolver_match.kwargs.get('object_id'):
|
if hasattr(request, 'resolver_match') and request.resolver_match.kwargs.get('object_id'):
|
||||||
album_id = request.resolver_match.kwargs['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)
|
return super().formfield_for_foreignkey(db_field, request, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
# 🔹 PhotoAdmin – kuvien hallinta
|
||||||
class PhotoAdmin(admin.ModelAdmin):
|
class PhotoAdmin(admin.ModelAdmin):
|
||||||
list_display = ('slug', 'album', 'is_favorite', 'admin_thumbnail')
|
list_display = ('slug', 'album', 'is_favorite', 'admin_thumbnail')
|
||||||
list_display_links = ('slug',)
|
list_display_links = ('slug',)
|
||||||
|
@ -136,6 +150,7 @@ class PhotoAdmin(admin.ModelAdmin):
|
||||||
list_editable = ('is_favorite',)
|
list_editable = ('is_favorite',)
|
||||||
|
|
||||||
|
|
||||||
|
# 🔹 Rekisteröidään admin-paneeliin
|
||||||
admin.site.register(City, CityAdmin)
|
admin.site.register(City, CityAdmin)
|
||||||
admin.site.register(Location, LocationAdmin)
|
admin.site.register(Location, LocationAdmin)
|
||||||
admin.site.register(Album, AlbumAdmin)
|
admin.site.register(Album, AlbumAdmin)
|
||||||
|
|
|
@ -1,114 +1,162 @@
|
||||||
{% extends "admin/base_site.html" %}
|
{% extends "admin/base_site.html" %}
|
||||||
{% block content %}
|
{% block content %}
|
||||||
<div class="container mt-3">
|
<div class="module">
|
||||||
<h1>Upload Photos to {{ album.name }}</h1>
|
<h2>Upload Photos to {{ album.name }}</h2>
|
||||||
|
|
||||||
<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>
|
|
||||||
|
|
||||||
<form id="upload-form" method="post" enctype="multipart/form-data">
|
<form id="upload-form" method="post" enctype="multipart/form-data">
|
||||||
{% csrf_token %}
|
{% csrf_token %}
|
||||||
|
|
||||||
<div class="uk-margin">
|
<div class="form-row">
|
||||||
<div id="js-drop" class="uk-placeholder uk-text-center uk-margin-medium-top">
|
<div id="js-drop" class="drop-area">
|
||||||
<span uk-icon="icon: cloud-upload"></span>
|
<p><strong>Drag files here</strong> or click below to select</p>
|
||||||
<span class="uk-text-middle">Drag files here or</span>
|
<input id="file-input" type="file" name="photo" multiple accept=".jpg,.jpeg">
|
||||||
<div uk-form-custom>
|
|
||||||
<input id="file-input" type="file" name="photo" multiple accept=".jpg,.jpeg">
|
|
||||||
<span class="uk-link">select them</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<ul id="file-list" class="uk-list uk-list-divider"></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>
|
</div>
|
||||||
|
|
||||||
<button id="upload-button" class="uk-button uk-button-primary" type="button">Upload</button>
|
<ul id="file-list" class="messagelist"></ul>
|
||||||
|
<p>Total size: <span id="total-size">0</span> MB</p>
|
||||||
|
|
||||||
|
<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>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script>
|
<style>
|
||||||
const fileInput = document.getElementById('file-input');
|
.drop-area {
|
||||||
const fileList = document.getElementById('file-list');
|
border: 2px dashed #ddd;
|
||||||
const totalSizeElement = document.getElementById('total-size');
|
padding: 20px;
|
||||||
const uploadButton = document.getElementById('upload-button');
|
text-align: center;
|
||||||
const progressBar = document.getElementById('js-progressbar');
|
background: #f9f9f9;
|
||||||
const dropArea = document.getElementById('js-drop');
|
cursor: pointer;
|
||||||
let filesToUpload = [];
|
margin-bottom: 10px;
|
||||||
let totalSize = 0;
|
transition: background 0.3s, border-color 0.3s;
|
||||||
|
|
||||||
function updateFileList(newFiles) {
|
|
||||||
filesToUpload = [...newFiles].filter(file => file.name.match(/\.jpe?g$/i));
|
|
||||||
fileList.innerHTML = '';
|
|
||||||
totalSize = filesToUpload.reduce((acc, file) => acc + file.size, 0);
|
|
||||||
|
|
||||||
filesToUpload.forEach(file => {
|
|
||||||
const listItem = document.createElement('li');
|
|
||||||
listItem.textContent = `${file.name} (${(file.size / (1024 * 1024)).toFixed(2)} MB)`;
|
|
||||||
fileList.appendChild(listItem);
|
|
||||||
});
|
|
||||||
totalSizeElement.textContent = (totalSize / (1024 * 1024)).toFixed(2);
|
|
||||||
}
|
}
|
||||||
|
.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>
|
||||||
|
|
||||||
fileInput.addEventListener('change', event => updateFileList(event.target.files));
|
<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');
|
||||||
|
|
||||||
['dragenter', 'dragover'].forEach(eventName => dropArea.addEventListener(eventName, e => {
|
let filesToUpload = [];
|
||||||
e.preventDefault();
|
let totalSize = 0;
|
||||||
dropArea.classList.add('uk-active');
|
const maxSize = 10 * 1024 * 1024; // 10MB per file
|
||||||
}));
|
|
||||||
|
|
||||||
['dragleave', 'drop'].forEach(eventName => dropArea.addEventListener(eventName, e => {
|
function updateFileList(newFiles) {
|
||||||
e.preventDefault();
|
// Suodatetaan vain JPEG-tiedostot ja poistetaan liian suuret
|
||||||
dropArea.classList.remove('uk-active');
|
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;
|
||||||
|
});
|
||||||
|
|
||||||
dropArea.addEventListener('drop', event => {
|
fileList.innerHTML = '';
|
||||||
updateFileList(event.dataTransfer.files);
|
totalSize = filesToUpload.reduce((acc, file) => acc + file.size, 0);
|
||||||
});
|
|
||||||
|
|
||||||
uploadButton.addEventListener('click', () => {
|
filesToUpload.forEach(file => {
|
||||||
if (filesToUpload.length === 0) {
|
const listItem = document.createElement('li');
|
||||||
alert('Please select files to upload.');
|
listItem.textContent = `${file.name} (${(file.size / (1024 * 1024)).toFixed(2)} MB)`;
|
||||||
return;
|
fileList.appendChild(listItem);
|
||||||
|
});
|
||||||
|
|
||||||
|
totalSizeElement.textContent = (totalSize / (1024 * 1024)).toFixed(2);
|
||||||
}
|
}
|
||||||
|
|
||||||
progressBar.hidden = false;
|
fileInput.addEventListener('change', event => updateFileList(event.target.files));
|
||||||
let uploaded = 0;
|
|
||||||
|
|
||||||
filesToUpload.forEach((file, index) => {
|
['dragenter', 'dragover'].forEach(eventName => dropArea.addEventListener(eventName, e => {
|
||||||
const xhr = new XMLHttpRequest();
|
e.preventDefault();
|
||||||
const formData = new FormData();
|
dropArea.classList.add('dragover');
|
||||||
formData.append('photo', file);
|
}));
|
||||||
formData.append('csrfmiddlewaretoken', '{{ csrf_token }}');
|
|
||||||
xhr.open('POST', '', true);
|
|
||||||
|
|
||||||
xhr.upload.onprogress = event => {
|
['dragleave', 'drop'].forEach(eventName => dropArea.addEventListener(eventName, e => {
|
||||||
if (event.lengthComputable) {
|
e.preventDefault();
|
||||||
progressBar.value = ((uploaded + event.loaded) / totalSize) * 100;
|
dropArea.classList.remove('dragover');
|
||||||
}
|
}));
|
||||||
};
|
|
||||||
|
|
||||||
xhr.onload = () => {
|
dropArea.addEventListener('drop', event => {
|
||||||
const listItem = fileList.children[index];
|
updateFileList(event.dataTransfer.files);
|
||||||
if (xhr.status === 200) {
|
});
|
||||||
listItem.textContent += ' - Upload successful!';
|
|
||||||
listItem.classList.add('uk-text-success');
|
uploadButton.addEventListener('click', () => {
|
||||||
} else {
|
if (filesToUpload.length === 0) {
|
||||||
|
alert('Please select files to upload.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
progressBar.hidden = false;
|
||||||
|
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 = ((uploadedSize + event.loaded) / totalSize) * 100;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
xhr.onload = () => {
|
||||||
|
const listItem = fileList.children[index];
|
||||||
|
if (xhr.status === 200) {
|
||||||
|
listItem.textContent += ' - Upload successful!';
|
||||||
|
listItem.classList.add('success');
|
||||||
|
} else {
|
||||||
|
listItem.textContent += ' - Upload failed!';
|
||||||
|
listItem.classList.add('error');
|
||||||
|
}
|
||||||
|
uploadedSize += file.size;
|
||||||
|
};
|
||||||
|
|
||||||
|
xhr.onerror = () => {
|
||||||
|
const listItem = fileList.children[index];
|
||||||
listItem.textContent += ' - Upload failed!';
|
listItem.textContent += ' - Upload failed!';
|
||||||
listItem.classList.add('uk-text-danger');
|
listItem.classList.add('error');
|
||||||
}
|
};
|
||||||
uploaded += file.size;
|
|
||||||
};
|
|
||||||
|
|
||||||
xhr.onerror = () => {
|
xhr.send(formData);
|
||||||
fileList.children[index].textContent += ' - Upload failed!';
|
});
|
||||||
fileList.children[index].classList.add('uk-text-danger');
|
|
||||||
};
|
|
||||||
|
|
||||||
xhr.send(formData);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
{% endblock %}
|
{% endblock %}
|
Loading…
Add table
Reference in a new issue