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):
self.name_slug = re.sub('[^a-zA-Z0-9]', '-', self.name).strip('-').lower()
self.name_slug = re.sub('[-]+', '-', self.name_slug)
super(File, self).save()
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}
if orignal_nzb not in renamed_nzb:
if os.path.isfile(renamed_nzb):
os.remove(renamed_nzb)
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
?