Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

django rest framework delete file

import os
import uuid

from django.db import models
from django.dispatch import receiver
from django.utils.translation import ugettext_lazy as _


class MediaFile(models.Model):
    file = models.FileField(_("file"),
        upload_to=lambda instance, filename: str(uuid.uuid4()))


# These two auto-delete files from filesystem when they are unneeded:

@receiver(models.signals.post_delete, sender=MediaFile)
def auto_delete_file_on_delete(sender, instance, **kwargs):
    """
    Deletes file from filesystem
    when corresponding `MediaFile` object is deleted.
    """
    if instance.file:
        if os.path.isfile(instance.file.path):
            os.remove(instance.file.path)

@receiver(models.signals.pre_save, sender=MediaFile)
def auto_delete_file_on_change(sender, instance, **kwargs):
    """
    Deletes old file from filesystem
    when corresponding `MediaFile` object is updated
    with new file.
    """
    if not instance.pk:
        return False

    try:
        old_file = MediaFile.objects.get(pk=instance.pk).file
    except MediaFile.DoesNotExist:
        return False

    new_file = instance.file
    if not old_file == new_file:
        if os.path.isfile(old_file.path):
            os.remove(old_file.path)
Comment

PREVIOUS NEXT
Code Example
Python :: how to ask someone for their name in python 
Python :: python diamond pattern 
Python :: replace column values pandas 
Python :: generate random prime number python 
Python :: matplotlib axes limits 
Python :: print matrix eleme 
Python :: python min length list of strings 
Python :: write csv python pandas stack overflow 
Python :: rock paper scissors game in python 
Python :: pandas create dataframe of ones 
Python :: python how to check which int var is the greatest 
Python :: python selenium button is not clickable at point 
Python :: how to know how much lines a file has using python 
Python :: get text from table tag beautifulsoup 
Python :: python test if value is np.nan 
Python :: primes in python 
Python :: plt turn legend off 
Python :: how to change colour of rows in csv using pandas 
Python :: pandas create a column from index 
Python :: python open dicom 
Python :: set_interval() 
Python :: python json indented 
Python :: python sum of digits in a string 
Python :: key item loop list python 
Python :: change tick labelsize matplotlib 
Python :: polynomial features random forest classifier 
Python :: extract image from pdf python 
Python :: python random phone number 
Python :: selenium refresh till the element appears python 
Python :: python http server command line 
ADD CONTENT
Topic
Content
Source link
Name
8+6 =