photos fix

This commit is contained in:
pacnpal
2024-11-01 01:27:11 +00:00
parent 80a9d61ca2
commit f51c8370ce
89 changed files with 2241 additions and 614 deletions

View File

@@ -0,0 +1,26 @@
# Generated by Django 5.1.2 on 2024-11-01 00:24
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("media", "0001_initial"),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.AddField(
model_name="photo",
name="uploaded_by",
field=models.ForeignKey(
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name="uploaded_photos",
to=settings.AUTH_USER_MODEL,
),
),
]

View File

@@ -0,0 +1,69 @@
from django.db import migrations, models
import os
from django.db import transaction
def normalize_filenames(apps, schema_editor):
Photo = apps.get_model('media', 'Photo')
db_alias = schema_editor.connection.alias
# Get all photos
photos = Photo.objects.using(db_alias).all()
for photo in photos:
try:
with transaction.atomic():
# Get content type model name
content_type_model = photo.content_type.model
# Get current filename and extension
old_path = photo.image.name
_, ext = os.path.splitext(old_path)
if not ext:
ext = '.jpg' # Default to .jpg if no extension
ext = ext.lower()
# Get the photo number (based on creation order)
photo_number = Photo.objects.using(db_alias).filter(
content_type=photo.content_type,
object_id=photo.object_id,
created_at__lte=photo.created_at
).count()
# Extract identifier from current path
parts = old_path.split('/')
if len(parts) >= 2:
identifier = parts[1] # e.g., "alton-towers" from "park/alton-towers/..."
# Create new normalized filename
new_filename = f"{identifier}_{photo_number}{ext}"
new_path = f"{content_type_model}/{identifier}/{new_filename}"
# Update the image field if path would change
if old_path != new_path:
photo.image.name = new_path
photo.save(using=db_alias)
except Exception as e:
print(f"Error normalizing photo {photo.id}: {str(e)}")
# Continue with next photo even if this one fails
continue
def reverse_normalize(apps, schema_editor):
# No reverse operation needed since we're just renaming files
pass
class Migration(migrations.Migration):
dependencies = [
('media', '0002_photo_uploaded_by'),
]
operations = [
# First increase the field length
migrations.AlterField(
model_name='photo',
name='image',
field=models.ImageField(max_length=255, upload_to='photos'),
),
# Then normalize the filenames
migrations.RunPython(normalize_filenames, reverse_normalize),
]

View File

@@ -0,0 +1,10 @@
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('media', '0003_update_photo_field_and_normalize'),
]
operations = [
# No schema changes needed, just need to trigger the new upload_to path
]