Django: the uploaded file is locked. Unable to rename

I am trying to rename a file after uploading it to a model save method. I rename the file to a combination of the primary key of the files and the bullet of the file name.

It works for me when the file is downloaded first, when a new file is loaded, and when there is no change in the name of the file or file.

However, when the file name changes and the system tries to rename the old file to a new path, I get the following error:

WindowsError at /admin/main/file/1/
(32, 'The process cannot access the file because it is being used by another process')

I do not know how to get around this. I tried just copying the file to a new path. This works, but I don’t know that I can remove the old version.

Shortened model:

class File(models.Model):
    nzb = models.FileField(upload_to='files/')
    name = models.CharField(max_length=256)
    name_slug = models.CharField(max_length=256, blank=True, null=True, editable=False)

    def save(self):
        # Create the name slug.
        self.name_slug = re.sub('[^a-zA-Z0-9]', '-', self.name).strip('-').lower()
        self.name_slug = re.sub('[-]+', '-', self.name_slug)

        # Need the primary key for naming the file.
        super(File, self).save()

        # Create the system paths we need.
        orignal_nzb = u'%(1)s%(2)s' % {'1': settings.MEDIA_ROOT, '2': self.nzb}
        renamed_nzb = u'%(1)sfiles/%(2)s_%(3)s.nzb' % {'1': settings.MEDIA_ROOT, '2': self.pk, '3': self.name_slug}

        # Rename the file.
        if orignal_nzb not in renamed_nzb:
            if os.path.isfile(renamed_nzb):
                os.remove(renamed_nzb)

            # Fails when name is updated.
            os.rename(orignal_nzb, renamed_nzb)

        self.nzb = 'files/%(1)s_%(2)s.nzb' % {'1': self.pk, '2': self.name_slug}

        super(File, self).save()

, : - , , ? , /.


Update:

Tyler , , , , .

if not instance.pk:
    instance.save()

:

maximum recursion depth exceeded while calling a Python object

?

+3
3

, upload_to. , , , .

http://docs.djangoproject.com/en/dev/ref/models/fields/#filefield

, , , , . Unix ( ) . , :

+5

, :

class File(models.Model):
    nzb = models.FileField(upload_to=get_filename)
    ...
    def get_filename(instance, filename):
        if not instance.pk:
            instance.save()
        # Create the name slug.
        name_slug = re.sub('[^a-zA-Z0-9]', '-', instance.name).strip('-').lower()
        name_slug = re.sub('[-]+', '-', name_slug)

        filename = u'filess/%(2)s_%(3)s.nzb' % {'2': instance.pk, '3': name_slug}

        return filename

1.0, upload_to , , ( MEDIA_ROOT).

+3

, , , ?

, .

Django ORM -, Django.

0

Source: https://habr.com/ru/post/1704625/


All Articles