okay fine

This commit is contained in:
pacnpal
2024-11-03 17:47:26 +00:00
parent 01c6004a79
commit 27eb239e97
10020 changed files with 1935769 additions and 2364 deletions

View File

@@ -1,99 +0,0 @@
from django.core.management.base import BaseCommand
from django.db import connection
class Command(BaseCommand):
help = 'Fix historical park records with null location values'
def handle(self, *args, **options):
with connection.cursor() as cursor:
# Make fields nullable temporarily
self.stdout.write('Making fields nullable...')
cursor.execute("""
ALTER TABLE parks_historicalpark
ALTER COLUMN city_id DROP NOT NULL,
ALTER COLUMN region_id DROP NOT NULL,
ALTER COLUMN country_id DROP NOT NULL,
ALTER COLUMN location DROP NOT NULL;
""")
# Get or create default locations
self.stdout.write('Creating default locations if needed...')
# Check if Unknown country exists
cursor.execute("SELECT id FROM cities_light_country WHERE name = 'Unknown' LIMIT 1;")
result = cursor.fetchone()
if not result:
cursor.execute("""
INSERT INTO cities_light_country (name, name_ascii, slug, geoname_id, alternate_names, display_name, search_names)
VALUES ('Unknown', 'Unknown', 'unknown', 0, '', 'Unknown', 'Unknown')
RETURNING id;
""")
default_country_id = cursor.fetchone()[0]
else:
default_country_id = result[0]
# Check if Unknown region exists
cursor.execute("""
SELECT id FROM cities_light_region
WHERE name = 'Unknown' AND country_id = %s LIMIT 1;
""", [default_country_id])
result = cursor.fetchone()
if not result:
cursor.execute("""
INSERT INTO cities_light_region (name, name_ascii, slug, geoname_id, alternate_names, country_id, display_name, search_names)
VALUES ('Unknown', 'Unknown', 'unknown', 0, '', %s, 'Unknown', 'Unknown')
RETURNING id;
""", [default_country_id])
default_region_id = cursor.fetchone()[0]
else:
default_region_id = result[0]
# Check if Unknown city exists
cursor.execute("""
SELECT id FROM cities_light_city
WHERE name = 'Unknown' AND region_id = %s LIMIT 1;
""", [default_region_id])
result = cursor.fetchone()
if not result:
cursor.execute("""
INSERT INTO cities_light_city (
name, name_ascii, slug, geoname_id, alternate_names,
region_id, country_id, display_name, search_names,
latitude, longitude, population
)
VALUES (
'Unknown', 'Unknown', 'unknown', 0, '',
%s, %s, 'Unknown', 'Unknown',
0, 0, 0
)
RETURNING id;
""", [default_region_id, default_country_id])
default_city_id = cursor.fetchone()[0]
else:
default_city_id = result[0]
# Update historical records with null values
self.stdout.write('Updating historical records...')
cursor.execute("""
UPDATE parks_historicalpark
SET country_id = %s,
region_id = %s,
city_id = %s,
location = 'Unknown, Unknown, Unknown'
WHERE country_id IS NULL
OR region_id IS NULL
OR city_id IS NULL
OR location IS NULL;
""", [default_country_id, default_region_id, default_city_id])
# Make fields non-nullable again
self.stdout.write('Making fields non-nullable...')
cursor.execute("""
ALTER TABLE parks_historicalpark
ALTER COLUMN city_id SET NOT NULL,
ALTER COLUMN region_id SET NOT NULL,
ALTER COLUMN country_id SET NOT NULL,
ALTER COLUMN location SET NOT NULL;
""")
self.stdout.write(self.style.SUCCESS('Successfully fixed historical records'))

View File

@@ -1,90 +0,0 @@
from django.core.management.base import BaseCommand
from django.db import connection
class Command(BaseCommand):
help = 'Fix location fields in parks and historical records'
def handle(self, *args, **options):
with connection.cursor() as cursor:
# Check if Unknown country exists
cursor.execute("""
SELECT id FROM cities_light_country WHERE name = 'Unknown' LIMIT 1;
""")
result = cursor.fetchone()
if result:
default_country_id = result[0]
else:
cursor.execute("""
INSERT INTO cities_light_country (name, name_ascii, slug, geoname_id, alternate_names)
VALUES ('Unknown', 'Unknown', 'unknown', 0, '')
RETURNING id;
""")
default_country_id = cursor.fetchone()[0]
# Check if Unknown region exists
cursor.execute("""
SELECT id FROM cities_light_region
WHERE name = 'Unknown' AND country_id = %s LIMIT 1;
""", [default_country_id])
result = cursor.fetchone()
if result:
default_region_id = result[0]
else:
cursor.execute("""
INSERT INTO cities_light_region (name, name_ascii, slug, geoname_id, alternate_names, country_id, display_name)
VALUES ('Unknown', 'Unknown', 'unknown', 0, '', %s, 'Unknown')
RETURNING id;
""", [default_country_id])
default_region_id = cursor.fetchone()[0]
# Check if Unknown city exists
cursor.execute("""
SELECT id FROM cities_light_city
WHERE name = 'Unknown' AND region_id = %s LIMIT 1;
""", [default_region_id])
result = cursor.fetchone()
if result:
default_city_id = result[0]
else:
cursor.execute("""
INSERT INTO cities_light_city (
name, name_ascii, slug, geoname_id, alternate_names,
region_id, country_id, display_name,
latitude, longitude, population
)
VALUES (
'Unknown', 'Unknown', 'unknown', 0, '',
%s, %s, 'Unknown',
0, 0, 0
)
RETURNING id;
""", [default_region_id, default_country_id])
default_city_id = cursor.fetchone()[0]
# Update parks with null locations
cursor.execute("""
UPDATE parks_park
SET country_id = %s,
region_id = %s,
city_id = %s,
location = 'Unknown, Unknown, Unknown'
WHERE country_id IS NULL
OR region_id IS NULL
OR city_id IS NULL
OR location IS NULL;
""", [default_country_id, default_region_id, default_city_id])
# Update historical records with null locations
cursor.execute("""
UPDATE parks_historicalpark
SET country_id = %s,
region_id = %s,
city_id = %s,
location = 'Unknown, Unknown, Unknown'
WHERE country_id IS NULL
OR region_id IS NULL
OR city_id IS NULL
OR location IS NULL;
""", [default_country_id, default_region_id, default_city_id])
self.stdout.write(self.style.SUCCESS('Successfully fixed location fields'))

View File

@@ -0,0 +1,28 @@
from django.core.management.base import BaseCommand
from django.db import connection
class Command(BaseCommand):
help = 'Fix migration history'
def handle(self, *args, **options):
with connection.cursor() as cursor:
# Drop existing historical tables
cursor.execute("""
DROP TABLE IF EXISTS parks_historicalpark CASCADE;
DROP TABLE IF EXISTS parks_historicalparkarea CASCADE;
""")
# Delete all existing parks migrations
cursor.execute("""
DELETE FROM django_migrations
WHERE app = 'parks';
""")
# Insert the new initial migration
cursor.execute("""
INSERT INTO django_migrations (app, name, applied)
VALUES ('parks', '0001_initial', NOW());
""")
self.stdout.write(self.style.SUCCESS('Successfully fixed migration history'))

View File

@@ -1,5 +1,6 @@
import json
import os
import shutil
from django.core.management.base import BaseCommand
from django.contrib.auth import get_user_model
from django.contrib.contenttypes.models import ContentType
@@ -11,128 +12,180 @@ from rides.models import Ride, RollerCoasterStats
from companies.models import Company, Manufacturer
from reviews.models import Review
from media.models import Photo
from cities_light.models import Country, Region, City
from django.contrib.auth.models import Permission
import random
from datetime import datetime, timedelta
User = get_user_model()
# Park coordinates mapping
PARK_COORDINATES = {
"Walt Disney World Magic Kingdom": {
"latitude": "28.418778",
"longitude": "-81.581212",
"street_address": "1180 Seven Seas Dr",
"city": "Orlando",
"state": "Florida",
"postal_code": "32836"
},
"Cedar Point": {
"latitude": "41.482207",
"longitude": "-82.683523",
"street_address": "1 Cedar Point Dr",
"city": "Sandusky",
"state": "Ohio",
"postal_code": "44870"
},
"Universal's Islands of Adventure": {
"latitude": "28.470891",
"longitude": "-81.471756",
"street_address": "6000 Universal Blvd",
"city": "Orlando",
"state": "Florida",
"postal_code": "32819"
},
"Alton Towers": {
"latitude": "52.988889",
"longitude": "-1.892778",
"street_address": "Farley Ln",
"city": "Alton",
"state": "Staffordshire",
"postal_code": "ST10 4DB"
},
"Europa-Park": {
"latitude": "48.266031",
"longitude": "7.722044",
"street_address": "Europa-Park-Straße 2",
"city": "Rust",
"state": "Baden-Württemberg",
"postal_code": "77977"
}
}
class Command(BaseCommand):
help = 'Seeds the database with initial data'
help = "Seeds the database with initial data"
def handle(self, *args, **kwargs):
self.stdout.write('Starting database seed...')
self.stdout.write("Starting database seed...")
# Clean up media directory
self.stdout.write("Cleaning up media directory...")
media_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), 'media')
if os.path.exists(media_dir):
for item in os.listdir(media_dir):
if item != '__init__.py': # Preserve __init__.py
item_path = os.path.join(media_dir, item)
if os.path.isdir(item_path):
shutil.rmtree(item_path)
else:
os.remove(item_path)
# Delete all existing data
self.stdout.write("Deleting existing data...")
User.objects.exclude(username='admin').delete() # Delete all users except admin
Park.objects.all().delete()
Ride.objects.all().delete()
Company.objects.all().delete()
Manufacturer.objects.all().delete()
Review.objects.all().delete()
Photo.objects.all().delete()
# Create users and set permissions
self.create_users()
self.setup_permissions()
# Create parks and rides
self.stdout.write('Creating parks and rides from seed data...')
self.stdout.write("Creating parks and rides from seed data...")
self.create_companies()
self.create_manufacturers()
self.create_parks_and_rides()
# Create reviews
self.stdout.write('Creating reviews...')
self.stdout.write("Creating reviews...")
self.create_reviews()
# Create top lists
self.stdout.write('Creating top lists...')
self.create_top_lists()
self.stdout.write('Successfully seeded database')
self.stdout.write("Successfully seeded database")
def setup_permissions(self):
"""Set up photo permissions for all users"""
self.stdout.write('Setting up photo permissions...')
self.stdout.write("Setting up photo permissions...")
# Get photo permissions
photo_content_type = ContentType.objects.get_for_model(Photo)
photo_permissions = Permission.objects.filter(content_type=photo_content_type)
# Update all users
users = User.objects.all()
for user in users:
for perm in photo_permissions:
user.user_permissions.add(perm)
user.save()
self.stdout.write(f'Updated permissions for user: {user.username}')
self.stdout.write(f"Updated permissions for user: {user.username}")
def create_users(self):
self.stdout.write('Creating users...')
self.stdout.write("Creating users...")
# Try to get admin user
try:
admin = User.objects.get(username='admin')
self.stdout.write('Admin user exists, updating permissions...')
admin = User.objects.get(username="admin")
self.stdout.write("Admin user exists, updating permissions...")
except User.DoesNotExist:
admin = User.objects.create_superuser('admin', 'admin@example.com', 'admin')
self.stdout.write('Created admin user')
# Create regular users
admin = User.objects.create_superuser("admin", "admin@example.com", "admin")
self.stdout.write("Created admin user")
# Create 10 regular users
usernames = [
'destiny89', 'destiny97', 'thompsonchris', 'chriscohen', 'littlesharon',
'wrichardson', 'christophermiles', 'jacksonangela', 'jennifer71', 'smithemily',
'brandylong', 'milleranna', 'tlopez', 'fgriffith', 'mariah80',
'kendradavis', 'rosarioashley', 'camposkaitlyn', 'lisaherrera', 'riveratiffany',
'codytucker', 'cheyenne78', 'christinagreen', 'eric57', 'steinsuzanne',
'david95', 'rstewart', 'josephhaynes', 'umedina', 'tylerbryant',
'lcampos', 'shellyford', 'ksmith', 'qeverett', 'waguilar',
'zbrowning', 'yalexander', 'wallacewilliam', 'bsuarez', 'ismith',
'joyceosborne', 'garythomas', 'tlewis', 'robertgonzales', 'medinashannon',
'yhanson', 'howellmorgan', 'taylorsusan', 'barnold', 'bryan20'
"thrillseeker1",
"coasterrider2",
"parkfan3",
"adventurer4",
"funseeker5",
"parkexplorer6",
"ridetester7",
"themepark8",
"coaster9",
"parkvisitor10"
]
for username in usernames:
if not User.objects.filter(username=username).exists():
User.objects.create_user(
username=username,
email=f'{username}@example.com',
password='password123'
)
self.stdout.write(f'Created user: {username}')
User.objects.create_user(
username=username,
email=f"{username}@example.com",
[PASSWORD-REMOVED]",
)
self.stdout.write(f"Created user: {username}")
def create_companies(self):
self.stdout.write('Creating companies...')
# Delete existing companies
Company.objects.all().delete()
self.stdout.write('Deleted existing companies')
self.stdout.write("Creating companies...")
companies = [
'The Walt Disney Company',
'Cedar Fair',
'NBCUniversal',
'Merlin Entertainments',
'Mack Rides'
"The Walt Disney Company",
"Cedar Fair",
"NBCUniversal",
"Merlin Entertainments",
"Mack Rides",
]
for name in companies:
Company.objects.create(name=name)
self.stdout.write(f'Created company: {name}')
self.stdout.write(f"Created company: {name}")
def create_manufacturers(self):
self.stdout.write('Creating manufacturers...')
# Delete existing manufacturers
Manufacturer.objects.all().delete()
self.stdout.write('Deleted existing manufacturers')
self.stdout.write("Creating manufacturers...")
manufacturers = [
'Walt Disney Imagineering',
'Bolliger & Mabillard',
'Intamin',
'Rocky Mountain Construction',
'Vekoma',
'Mack Rides',
'Oceaneering International'
"Walt Disney Imagineering",
"Bolliger & Mabillard",
"Intamin",
"Rocky Mountain Construction",
"Vekoma",
"Mack Rides",
"Oceaneering International",
]
for name in manufacturers:
Manufacturer.objects.create(name=name)
self.stdout.write(f'Created manufacturer: {name}')
self.stdout.write(f"Created manufacturer: {name}")
def download_image(self, url):
"""Download image from URL and return as Django File object"""
@@ -145,98 +198,93 @@ class Command(BaseCommand):
return None
def create_parks_and_rides(self):
# Delete existing parks and rides
Park.objects.all().delete()
self.stdout.write('Deleted existing parks and rides')
# Load seed data
with open(os.path.join(os.path.dirname(__file__), 'seed_data.json')) as f:
with open(os.path.join(os.path.dirname(__file__), "seed_data.json")) as f:
data = json.load(f)
country_map = {
'US': 'United States',
'GB': 'United Kingdom',
'DE': 'Germany'
}
for park_data in data['parks']:
for park_data in data["parks"]:
try:
country = Country.objects.get(code2=park_data['country'])
# Create park
# Create park with location data
park_coords = PARK_COORDINATES[park_data["name"]]
park = Park.objects.create(
name=park_data['name'],
country=country,
opening_date=park_data['opening_date'],
status=park_data['status'],
description=park_data['description'],
website=park_data['website'],
owner=Company.objects.get(name=park_data['owner']),
size_acres=park_data['size_acres']
name=park_data["name"],
country=park_data["country"],
opening_date=park_data["opening_date"],
status=park_data["status"],
description=park_data["description"],
website=park_data["website"],
owner=Company.objects.get(name=park_data["owner"]),
size_acres=park_data["size_acres"],
# Add location fields
latitude=park_coords["latitude"],
longitude=park_coords["longitude"],
street_address=park_coords["street_address"],
city=park_coords["city"],
state=park_coords["state"],
postal_code=park_coords["postal_code"]
)
# Add park photos
for photo_url in park_data['photos']:
for photo_url in park_data["photos"]:
img_file = self.download_image(photo_url)
if img_file:
Photo.objects.create(
image=img_file,
content_type=ContentType.objects.get_for_model(park),
object_id=park.id,
is_primary=True # First photo is primary
is_primary=True, # First photo is primary
)
# Create rides
for ride_data in park_data['rides']:
for ride_data in park_data["rides"]:
ride = Ride.objects.create(
name=ride_data['name'],
name=ride_data["name"],
park=park,
category=ride_data['category'],
opening_date=ride_data['opening_date'],
status=ride_data['status'],
manufacturer=Manufacturer.objects.get(name=ride_data['manufacturer']),
description=ride_data['description']
category=ride_data["category"],
opening_date=ride_data["opening_date"],
status=ride_data["status"],
manufacturer=Manufacturer.objects.get(
name=ride_data["manufacturer"]
),
description=ride_data["description"],
)
# Add ride photos
for photo_url in ride_data['photos']:
for photo_url in ride_data["photos"]:
img_file = self.download_image(photo_url)
if img_file:
Photo.objects.create(
image=img_file,
content_type=ContentType.objects.get_for_model(ride),
object_id=ride.id,
is_primary=True # First photo is primary
is_primary=True, # First photo is primary
)
# Add coaster stats if present
if 'stats' in ride_data:
if "stats" in ride_data:
RollerCoasterStats.objects.create(
ride=ride,
height_ft=ride_data['stats']['height_ft'],
length_ft=ride_data['stats']['length_ft'],
speed_mph=ride_data['stats']['speed_mph'],
inversions=ride_data['stats']['inversions'],
ride_time_seconds=ride_data['stats']['ride_time_seconds']
height_ft=ride_data["stats"]["height_ft"],
length_ft=ride_data["stats"]["length_ft"],
speed_mph=ride_data["stats"]["speed_mph"],
inversions=ride_data["stats"]["inversions"],
ride_time_seconds=ride_data["stats"]["ride_time_seconds"],
)
self.stdout.write(f'Created park and rides: {park.name}')
except Country.DoesNotExist:
self.stdout.write(f'Country not found: {park_data["country"]}')
self.stdout.write(f"Created park and rides: {park.name}")
except Exception as e:
self.stdout.write(self.style.ERROR(f"Error creating park {park_data['name']}: {str(e)}"))
continue
def create_reviews(self):
# Delete existing reviews
Review.objects.all().delete()
self.stdout.write('Deleted existing reviews')
users = list(User.objects.exclude(username='admin'))
users = list(User.objects.exclude(username="admin"))
parks = list(Park.objects.all())
# Generate random dates within the last year
today = datetime.now().date()
one_year_ago = today - timedelta(days=365)
for park in parks:
# Create 3-5 reviews per park
num_reviews = random.randint(3, 5)
@@ -244,42 +292,14 @@ class Command(BaseCommand):
# Generate random visit date
days_offset = random.randint(0, 365)
visit_date = one_year_ago + timedelta(days=days_offset)
Review.objects.create(
user=random.choice(users),
content_type=ContentType.objects.get_for_model(park),
object_id=park.id,
title=f'Great experience at {park.name}',
content='Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
title=f"Great experience at {park.name}",
content="Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
rating=random.randint(7, 10),
visit_date=visit_date
visit_date=visit_date,
)
self.stdout.write(f'Created reviews for {park.name}')
def create_top_lists(self):
# Delete existing top lists
# TopList.objects.all().delete()
self.stdout.write('Deleted existing top lists')
users = list(User.objects.exclude(username='admin'))
parks = list(Park.objects.all())
for i, user in enumerate(users, 1):
# Create top list for every 10th user
if i % 10 == 0:
# top_list = TopList.objects.create(
# user=user,
# name=f"{user.username}'s Top Parks",
# description='My favorite theme parks'
# )
# Add 3-5 random parks
# selected_parks = random.sample(parks, random.randint(3, 5))
# for j, park in enumerate(selected_parks, 1):
# TopListItem.objects.create(
# top_list=top_list,
# content_type=ContentType.objects.get_for_model(park),
# object_id=park.id,
# rank=j
# )
self.stdout.write(f'Created top lists for {i}/50 users')
self.stdout.write(f"Created reviews for {park.name}")