I am using the following code to rename the filename path for a FileField in my model uploaded via a form:
class Document(models.Model):
document_date = models.DateField(null=True)
document_category = models.CharField(null=False, max_length=255, choices=DOCUMENT_CATEGORY_CHOICES)
document = models.FileField(upload_to='documents/', max_length=100)
def save(self, *args, **kwargs):
ext = os.path.splitext(self.document.name)[1]
date = str(self.document_date).replace('-', '')
category = self.document_category
self.document.name = '%s_%s%s' % (date, category, ext)
super().save(*args, **kwargs)
This is working fine for new records created, however when I update these records using a form the record is saved with new updated details (date and/or category) and my database reflects the new filename path, however the filename of the actual file in the folder is not updated.
Is anyone able to shed some light as to where I am going wrong and how I might be able to go about fixing this? Any help is much appreciated!
This is because the save()
method calls on every update operation.
What I understood from OP is, you only need the save()
method in two cases,
1. When a new entry created
2. When the document
field changed/updated.
So, try to change the save()
as below,
class Document(models.Model):
document_date = models.DateField(null=True)
document_category = models.CharField(null=False, max_length=255, choices=DOCUMENT_CATEGORY_CHOICES)
document = models.FileField(upload_to='documents/', max_length=100)
def save(self, *args, **kwargs):
if not self.id or not Document.objects.get(id=self.id).document == self.document:
ext = os.path.splitext(self.document.name)[1]
date = str(self.document_date).replace('-', '')
category = self.document_category
self.document.name = '%s_%s%s' % (date, category, ext)
super().save(*args, **kwargs)