Add rename_media management command
This commit is contained in:
parent
4fa1f2f2df
commit
19eb5a420e
1 changed files with 38 additions and 0 deletions
38
photologue_custom/management/commands/rename_media.py
Normal file
38
photologue_custom/management/commands/rename_media.py
Normal file
|
|
@ -0,0 +1,38 @@
|
||||||
|
from pathlib import Path
|
||||||
|
import os
|
||||||
|
|
||||||
|
from django.core.management.base import BaseCommand
|
||||||
|
from photologue.models import Gallery
|
||||||
|
from django.conf import settings
|
||||||
|
from tqdm import tqdm
|
||||||
|
|
||||||
|
|
||||||
|
class Command(BaseCommand):
|
||||||
|
help = 'Rename uploaded media file to match gallery and photo names'
|
||||||
|
|
||||||
|
def add_arguments(self, parser):
|
||||||
|
parser.add_argument('--apply', action='store_true')
|
||||||
|
|
||||||
|
def handle(self, *args, **options):
|
||||||
|
media_dir = Path(settings.MEDIA_ROOT)
|
||||||
|
for gallery in tqdm(Gallery.objects.all()):
|
||||||
|
# Create gallery directory
|
||||||
|
gallery_year = str(gallery.extended.date_start.year)
|
||||||
|
gallery_dir = Path('photos') / gallery_year / gallery.slug
|
||||||
|
gallery_path = media_dir / gallery_dir
|
||||||
|
if not gallery_path.exists():
|
||||||
|
tqdm.write(f"Creating {gallery_dir}")
|
||||||
|
if options["apply"]:
|
||||||
|
gallery_path.mkdir(parents=True)
|
||||||
|
|
||||||
|
# Move photos in gallery folder
|
||||||
|
for photo in tqdm(gallery.photos.all()):
|
||||||
|
photo_name = str(gallery_dir / photo.image.name.split("/")[-1])
|
||||||
|
if photo.image.name == photo_name:
|
||||||
|
continue
|
||||||
|
tqdm.write(f" Moving {photo.image.name} -> {photo_name}")
|
||||||
|
if options["apply"]:
|
||||||
|
if not (media_dir / photo_name).exists():
|
||||||
|
os.rename(photo.image.path, media_dir / photo_name)
|
||||||
|
photo.image.name = photo_name
|
||||||
|
photo.save()
|
||||||
Loading…
Add table
Add a link
Reference in a new issue