Search code examples
djangofilefield

Renaming django FileField files


Some additional features were added to a django application, and as a result the upload_to function also expanded.

Since django by default stores filenames in the database, and files on disk, no harm has been done - new files are named using a new upload_to function, while old files continue to work.

However, this is messy - we end up in a situation with files like

/media/userID/oldfilename.pdf 

and

/media/app/userID/projectID/newfilename.pdf 

Is there a way to bulk rename those files? I guess it could be done by iterating through the database, checking if the path in FileField matches the result of current upload_to, and if not, rename.. it seems like a common problem, so perhaps there is a more generic way out there?


Solution

  • The simple solution is to write a custom Django management command. You can run the command using Django's standard manage.py.

    Something like this:

    from django.core.management.base import BaseCommand, CommandError
    from example.models import YourModel
    
    class Command(BaseCommand):
        args = ''
        help = ''
    
        def handle(self, *args, **options):
    
            # Get all objects
            objects = YourModel.objects.all()
    
            for object in objects: # For each object
    
                # If old file path:
                if not 'userID/projectID' in objects.filefield.name:
                    # Move the file, eg usign shutil http://docs.python.org/library/shutil.html#shutil.move
                    # Update filefield
                    # save object