Revert "update"

This reverts commit 75cc618c2b.
This commit is contained in:
pacnpal
2025-09-21 20:11:00 -04:00
parent 75cc618c2b
commit 540f40e689
610 changed files with 4812 additions and 1715 deletions

View File

View File

@@ -0,0 +1,54 @@
from django.apps import AppConfig
from django.db.models.signals import post_migrate
def create_photo_permissions(sender, **kwargs):
"""Create custom permissions for domain-specific photo models"""
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
from apps.parks.models import ParkPhoto
from apps.rides.models import RidePhoto
# Create permissions for ParkPhoto
park_photo_content_type = ContentType.objects.get_for_model(ParkPhoto)
Permission.objects.get_or_create(
codename="add_parkphoto",
name="Can add park photo",
content_type=park_photo_content_type,
)
Permission.objects.get_or_create(
codename="change_parkphoto",
name="Can change park photo",
content_type=park_photo_content_type,
)
Permission.objects.get_or_create(
codename="delete_parkphoto",
name="Can delete park photo",
content_type=park_photo_content_type,
)
# Create permissions for RidePhoto
ride_photo_content_type = ContentType.objects.get_for_model(RidePhoto)
Permission.objects.get_or_create(
codename="add_ridephoto",
name="Can add ride photo",
content_type=ride_photo_content_type,
)
Permission.objects.get_or_create(
codename="change_ridephoto",
name="Can change ride photo",
content_type=ride_photo_content_type,
)
Permission.objects.get_or_create(
codename="delete_ridephoto",
name="Can delete ride photo",
content_type=ride_photo_content_type,
)
class MediaConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "apps.media"
def ready(self):
post_migrate.connect(create_photo_permissions, sender=self)

View File

@@ -0,0 +1,126 @@
import requests
from django.core.management.base import BaseCommand
from apps.parks.models import Park, ParkPhoto
from apps.rides.models import Ride, RidePhoto
import json
from django.core.files.base import ContentFile
class Command(BaseCommand):
help = "Download photos from seed data URLs"
def handle(self, *args, **kwargs):
self.stdout.write("Downloading photos from seed data...")
# Read seed data
with open("parks/management/commands/seed_data.json", "r") as f:
seed_data = json.load(f)
# Process parks and their photos
for park_data in seed_data["parks"]:
try:
park = Park.objects.get(name=park_data["name"])
# Download park photos
for idx, photo_url in enumerate(park_data["photos"], 1):
try:
# Download image
self.stdout.write(f"Downloading from URL: {photo_url}")
response = requests.get(photo_url, timeout=60)
if response.status_code == 200:
# Delete any existing photos for this park
ParkPhoto.objects.filter(park=park).delete()
# Create new photo record
photo = ParkPhoto(
park=park,
is_primary=idx == 1,
)
# Save image content
photo.image.save(
f"{park.slug}_{idx}.jpg",
ContentFile(response.content),
save=False,
)
photo.save()
self.stdout.write(
f"Downloaded photo for {
park.name}: {
photo.image.name}"
)
self.stdout.write(
f"Database record created with ID: {photo.id}"
)
else:
self.stdout.write(
f"Error downloading image. Status code: {
response.status_code}"
)
except Exception as e:
self.stdout.write(
f"Error downloading park photo: {
str(e)}"
)
# Process rides and their photos
for ride_data in park_data["rides"]:
try:
ride = Ride.objects.get(name=ride_data["name"], park=park)
# Download ride photos
for idx, photo_url in enumerate(ride_data["photos"], 1):
try:
# Download image
self.stdout.write(f"Downloading from URL: {photo_url}")
response = requests.get(photo_url, timeout=60)
if response.status_code == 200:
# Delete any existing photos for this ride
RidePhoto.objects.filter(ride=ride).delete()
# Create new photo record
photo = RidePhoto(
ride=ride,
is_primary=idx == 1,
)
# Save image content
photo.image.save(
f"{ride.slug}_{idx}.jpg",
ContentFile(response.content),
save=False,
)
photo.save()
self.stdout.write(
f"Downloaded photo for {
ride.name}: {
photo.image.name}"
)
self.stdout.write(
f"Database record created with ID: {
photo.id}"
)
else:
self.stdout.write(
f"Error downloading image. Status code: {
response.status_code}"
)
except Exception as e:
self.stdout.write(
f"Error downloading ride photo: {str(e)}"
)
except Ride.DoesNotExist:
self.stdout.write(
f'Ride not found: {
ride_data["name"]}'
)
except Park.DoesNotExist:
self.stdout.write(f'Park not found: {park_data["name"]}')
self.stdout.write("Finished downloading photos")

View File

@@ -0,0 +1,142 @@
import os
from django.core.management.base import BaseCommand
from apps.parks.models import ParkPhoto
from apps.rides.models import RidePhoto
from django.db import transaction
class Command(BaseCommand):
help = "Fix photo paths in database to match actual file locations"
def handle(self, *args, **kwargs):
self.stdout.write("Fixing photo paths in database...")
# Get all photos
park_photos = ParkPhoto.objects.all()
ride_photos = RidePhoto.objects.all()
# Process park photos
for photo in park_photos:
try:
with transaction.atomic():
# Get current file path
current_name = photo.image.name
# Remove any 'media/' prefix if it exists
if current_name.startswith("media/"):
# Remove 'media/' prefix
current_name = current_name[6:]
parts = current_name.split("/")
if len(parts) >= 2:
content_type = "park"
identifier = photo.park.slug
# Look for files in the media directory
media_dir = os.path.join("media", content_type, identifier)
if os.path.exists(media_dir):
files = [
f
for f in os.listdir(media_dir)
if not f.startswith(".") # Skip hidden files
and not f.startswith("tmp") # Skip temp files
and os.path.isfile(os.path.join(media_dir, f))
]
if files:
# Get the first file and update the database
# record
file_path = os.path.join(
content_type, identifier, files[0]
)
if os.path.exists(os.path.join("media", file_path)):
photo.image.name = file_path
photo.save()
self.stdout.write(
f"Updated path for park photo {
photo.id} to {file_path}"
)
else:
self.stdout.write(
f"File not found for park photo {
photo.id}: {file_path}"
)
else:
self.stdout.write(
f"No files found in directory for park photo {
photo.id}: {media_dir}"
)
else:
self.stdout.write(
f"Directory not found for park photo {
photo.id}: {media_dir}"
)
except Exception as e:
self.stdout.write(f"Error updating park photo {photo.id}: {str(e)}")
continue
# Process ride photos
for photo in ride_photos:
try:
with transaction.atomic():
# Get current file path
current_name = photo.image.name
# Remove any 'media/' prefix if it exists
if current_name.startswith("media/"):
# Remove 'media/' prefix
current_name = current_name[6:]
parts = current_name.split("/")
if len(parts) >= 2:
content_type = "ride"
identifier = photo.ride.slug
# Look for files in the media directory
media_dir = os.path.join("media", content_type, identifier)
if os.path.exists(media_dir):
files = [
f
for f in os.listdir(media_dir)
if not f.startswith(".") # Skip hidden files
and not f.startswith("tmp") # Skip temp files
and os.path.isfile(os.path.join(media_dir, f))
]
if files:
# Get the first file and update the database
# record
file_path = os.path.join(
content_type, identifier, files[0]
)
if os.path.exists(os.path.join("media", file_path)):
photo.image.name = file_path
photo.save()
self.stdout.write(
f"Updated path for ride photo {
photo.id} to {file_path}"
)
else:
self.stdout.write(
f"File not found for ride photo {
photo.id}: {file_path}"
)
else:
self.stdout.write(
f"No files found in directory for ride photo {
photo.id}: {media_dir}"
)
else:
self.stdout.write(
f"Directory not found for ride photo {
photo.id}: {media_dir}"
)
except Exception as e:
self.stdout.write(f"Error updating ride photo {photo.id}: {str(e)}")
continue
self.stdout.write("Finished fixing photo paths")

View File

@@ -0,0 +1,197 @@
import os
from django.core.management.base import BaseCommand
from apps.parks.models import ParkPhoto
from apps.rides.models import RidePhoto
from django.conf import settings
import shutil
class Command(BaseCommand):
help = "Move photo files to their normalized locations"
def handle(self, *args, **kwargs):
self.stdout.write("Moving photo files to normalized locations...")
# Get all photos
park_photos = ParkPhoto.objects.all()
ride_photos = RidePhoto.objects.all()
# Track processed files to clean up later
processed_files = set()
# Process park photos
for photo in park_photos:
try:
# Get current file path
current_name = photo.image.name
current_path = os.path.join(settings.MEDIA_ROOT, current_name)
# Try to find the actual file
if not os.path.exists(current_path):
# Check if file exists in the old location structure
parts = current_name.split("/")
if len(parts) >= 2:
content_type = "park"
identifier = photo.park.slug
# Look for any files in that directory
old_dir = os.path.join(
settings.MEDIA_ROOT, content_type, identifier
)
if os.path.exists(old_dir):
files = [
f
for f in os.listdir(old_dir)
if not f.startswith(".") # Skip hidden files
and not f.startswith("tmp") # Skip temp files
and os.path.isfile(os.path.join(old_dir, f))
]
if files:
current_path = os.path.join(old_dir, files[0])
# Skip if file still not found
if not os.path.exists(current_path):
self.stdout.write(f"Skipping {current_name} - file not found")
continue
# Get content type and object
content_type_model = "park"
obj = photo.park
identifier = getattr(obj, "slug", obj.id)
# Get photo number
photo_number = ParkPhoto.objects.filter(
park=photo.park,
created_at__lte=photo.created_at,
).count()
# Create new filename
_, ext = os.path.splitext(current_path)
if not ext:
ext = ".jpg"
ext = ext.lower()
new_filename = f"{identifier}_{photo_number}{ext}"
# Create new path
new_relative_path = f"{content_type_model}/{identifier}/{new_filename}"
new_full_path = os.path.join(settings.MEDIA_ROOT, new_relative_path)
# Create directory if it doesn't exist
os.makedirs(os.path.dirname(new_full_path), exist_ok=True)
# Move the file
if current_path != new_full_path:
shutil.copy2(
current_path, new_full_path
) # Use copy2 to preserve metadata
processed_files.add(current_path)
else:
processed_files.add(current_path)
# Update database
photo.image.name = new_relative_path
photo.save()
self.stdout.write(f"Moved {current_name} to {new_relative_path}")
except Exception as e:
self.stdout.write(f"Error moving park photo {photo.id}: {str(e)}")
continue
# Process ride photos
for photo in ride_photos:
try:
# Get current file path
current_name = photo.image.name
current_path = os.path.join(settings.MEDIA_ROOT, current_name)
# Try to find the actual file
if not os.path.exists(current_path):
# Check if file exists in the old location structure
parts = current_name.split("/")
if len(parts) >= 2:
content_type = parts[0] # 'park' or 'ride'
identifier = parts[1] # e.g., 'alton-towers'
# Look for any files in that directory
old_dir = os.path.join(
settings.MEDIA_ROOT, content_type, identifier
)
if os.path.exists(old_dir):
files = [
f
for f in os.listdir(old_dir)
if not f.startswith(".") # Skip hidden files
and not f.startswith("tmp") # Skip temp files
and os.path.isfile(os.path.join(old_dir, f))
]
if files:
current_path = os.path.join(old_dir, files[0])
# Skip if file still not found
if not os.path.exists(current_path):
self.stdout.write(f"Skipping {current_name} - file not found")
continue
# Get content type and object
content_type_model = "ride"
obj = photo.ride
identifier = getattr(obj, "slug", obj.id)
# Get photo number
photo_number = RidePhoto.objects.filter(
ride=photo.ride,
created_at__lte=photo.created_at,
).count()
# Create new filename
_, ext = os.path.splitext(current_path)
if not ext:
ext = ".jpg"
ext = ext.lower()
new_filename = f"{identifier}_{photo_number}{ext}"
# Create new path
new_relative_path = f"{content_type_model}/{identifier}/{new_filename}"
new_full_path = os.path.join(settings.MEDIA_ROOT, new_relative_path)
# Create directory if it doesn't exist
os.makedirs(os.path.dirname(new_full_path), exist_ok=True)
# Move the file
if current_path != new_full_path:
shutil.copy2(
current_path, new_full_path
) # Use copy2 to preserve metadata
processed_files.add(current_path)
else:
processed_files.add(current_path)
# Update database
photo.image.name = new_relative_path
photo.save()
self.stdout.write(f"Moved {current_name} to {new_relative_path}")
except Exception as e:
self.stdout.write(f"Error moving ride photo {photo.id}: {str(e)}")
continue
# Clean up old files
self.stdout.write("Cleaning up old files...")
for content_type in ["park", "ride"]:
base_dir = os.path.join(settings.MEDIA_ROOT, content_type)
if os.path.exists(base_dir):
for root, dirs, files in os.walk(base_dir):
for file in files:
file_path = os.path.join(root, file)
if file_path not in processed_files:
try:
os.remove(file_path)
self.stdout.write(f"Removed old file: {file_path}")
except Exception as e:
self.stdout.write(
f"Error removing {file_path}: {str(e)}"
)
self.stdout.write("Finished moving photo files and cleaning up")

View File

@@ -0,0 +1,179 @@
# Generated by Django 5.1.4 on 2025-08-13 21:35
import django.db.models.deletion
import apps.media.models
import apps.media.storage
import pgtrigger.compiler
import pgtrigger.migrations
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
("contenttypes", "0002_remove_content_type_name"),
("pghistory", "0006_delete_aggregateevent"),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name="Photo",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
(
"image",
models.ImageField(
max_length=255,
storage=apps.media.storage.MediaStorage(),
upload_to=apps.media.models.photo_upload_path,
),
),
("caption", models.CharField(blank=True, max_length=255)),
("alt_text", models.CharField(blank=True, max_length=255)),
("is_primary", models.BooleanField(default=False)),
("is_approved", models.BooleanField(default=False)),
("created_at", models.DateTimeField(auto_now_add=True)),
("updated_at", models.DateTimeField(auto_now=True)),
("date_taken", models.DateTimeField(blank=True, null=True)),
("object_id", models.PositiveIntegerField()),
(
"content_type",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
to="contenttypes.contenttype",
),
),
(
"uploaded_by",
models.ForeignKey(
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name="uploaded_photos",
to=settings.AUTH_USER_MODEL,
),
),
],
options={
"ordering": ["-is_primary", "-created_at"],
},
),
migrations.CreateModel(
name="PhotoEvent",
fields=[
(
"pgh_id",
models.AutoField(primary_key=True, serialize=False),
),
("pgh_created_at", models.DateTimeField(auto_now_add=True)),
("pgh_label", models.TextField(help_text="The event label.")),
("id", models.BigIntegerField()),
(
"image",
models.ImageField(
max_length=255,
storage=apps.media.storage.MediaStorage(),
upload_to=apps.media.models.photo_upload_path,
),
),
("caption", models.CharField(blank=True, max_length=255)),
("alt_text", models.CharField(blank=True, max_length=255)),
("is_primary", models.BooleanField(default=False)),
("is_approved", models.BooleanField(default=False)),
("created_at", models.DateTimeField(auto_now_add=True)),
("updated_at", models.DateTimeField(auto_now=True)),
("date_taken", models.DateTimeField(blank=True, null=True)),
("object_id", models.PositiveIntegerField()),
(
"content_type",
models.ForeignKey(
db_constraint=False,
on_delete=django.db.models.deletion.DO_NOTHING,
related_name="+",
related_query_name="+",
to="contenttypes.contenttype",
),
),
(
"pgh_context",
models.ForeignKey(
db_constraint=False,
null=True,
on_delete=django.db.models.deletion.DO_NOTHING,
related_name="+",
to="pghistory.context",
),
),
(
"pgh_obj",
models.ForeignKey(
db_constraint=False,
on_delete=django.db.models.deletion.DO_NOTHING,
related_name="events",
to="media.photo",
),
),
(
"uploaded_by",
models.ForeignKey(
db_constraint=False,
null=True,
on_delete=django.db.models.deletion.DO_NOTHING,
related_name="+",
related_query_name="+",
to=settings.AUTH_USER_MODEL,
),
),
],
options={
"abstract": False,
},
),
migrations.AddIndex(
model_name="photo",
index=models.Index(
fields=["content_type", "object_id"],
name="media_photo_content_0187f5_idx",
),
),
pgtrigger.migrations.AddTrigger(
model_name="photo",
trigger=pgtrigger.compiler.Trigger(
name="insert_insert",
sql=pgtrigger.compiler.UpsertTriggerSql(
func='INSERT INTO "media_photoevent" ("alt_text", "caption", "content_type_id", "created_at", "date_taken", "id", "image", "is_approved", "is_primary", "object_id", "pgh_context_id", "pgh_created_at", "pgh_label", "pgh_obj_id", "updated_at", "uploaded_by_id") VALUES (NEW."alt_text", NEW."caption", NEW."content_type_id", NEW."created_at", NEW."date_taken", NEW."id", NEW."image", NEW."is_approved", NEW."is_primary", NEW."object_id", _pgh_attach_context(), NOW(), \'insert\', NEW."id", NEW."updated_at", NEW."uploaded_by_id"); RETURN NULL;',
hash="[AWS-SECRET-REMOVED]",
operation="INSERT",
pgid="pgtrigger_insert_insert_e1ca0",
table="media_photo",
when="AFTER",
),
),
),
pgtrigger.migrations.AddTrigger(
model_name="photo",
trigger=pgtrigger.compiler.Trigger(
name="update_update",
sql=pgtrigger.compiler.UpsertTriggerSql(
condition="WHEN (OLD.* IS DISTINCT FROM NEW.*)",
func='INSERT INTO "media_photoevent" ("alt_text", "caption", "content_type_id", "created_at", "date_taken", "id", "image", "is_approved", "is_primary", "object_id", "pgh_context_id", "pgh_created_at", "pgh_label", "pgh_obj_id", "updated_at", "uploaded_by_id") VALUES (NEW."alt_text", NEW."caption", NEW."content_type_id", NEW."created_at", NEW."date_taken", NEW."id", NEW."image", NEW."is_approved", NEW."is_primary", NEW."object_id", _pgh_attach_context(), NOW(), \'update\', NEW."id", NEW."updated_at", NEW."uploaded_by_id"); RETURN NULL;',
hash="[AWS-SECRET-REMOVED]",
operation="UPDATE",
pgid="pgtrigger_update_update_6ff7d",
table="media_photo",
when="AFTER",
),
),
),
]