Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
61 views
in Technique[技术] by (71.8m points)

python - How do you delete a Django Object after a given amount of time?

I'm a new Django developer, and working on a website where users can store csv files outputted by the website to a field of a model along with a randomly generated key. I referred to this link:

Delete an object automatically after 5 minutes

for more information, but when I implemented it onto my own project, it did not work.

from django.db import models
from django.utils import timezone
from django.conf import settings
import datetime
import os
# Create your models here.

class TemporaryFile(models.Model):
    key = models.CharField(max_length = 64)
    data = models.FileField()
    time_created = models.DateTimeField(default = timezone.now)

    @property
    def delete_after_time(self):
        if self.time_created < datetime.datetime.now()-datetime.timedelta(minutes=1):
            self_file = TemporaryFile.objects.get(pk = self.pk)
            data = self.data
            os.remove(os.path.join(MEDIA_ROOT, data))
            os.remove(os.path.join(BASE_DIR, data))
            self_file.delete()
            return True
        else:
            return False

Because it is difficult to store a csv file to a model field, I instead saved it to the default storage that Django has, which for some reason made two copies of the csv file and stored one in the media root and another one in the base directory. That is why I have the os.remove functions. Can somebody please tell me why the object and files are not being deleted?

question from:https://stackoverflow.com/questions/65516794/how-do-you-delete-a-django-object-after-a-given-amount-of-time

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...