SoFunction
Updated on 2024-10-29

Steps to delete upload_to file in Django

The new version of Django in the admin backend directly delete a piece of data, file = (upload_to = 'file') uploaded file will not be deleted, the following is the solution.

Before adding.

from  import pre_delete
from  import receiver
@receiver(pre_delete, sender=AddDateModel)
def mymodel_delete(sender, instance, **kwargs):
  # Pass false so FileField doesn't save the model.
  (False)

Additional knowledge:django's rewrite FileField field save example

Rewrite FileField field saving to rename as an example

Add Configuration

Add the following configuration at the end of the

# File upload rewrite
DEFAULT_FILE_STORAGE = ""

Add FileStorage

Under app application add python package customfilefield, note that there are files, under customfilefield create py file with the contents of the file:

# -*-coding:utf-8 -*-
from  import FileSystemStorage
from  import HttpResponse
from  import settings
import os, time, random
from app import utils
 
class FileStorage(FileSystemStorage):
  def __init__(self, location=settings.MEDIA_ROOT, base_url=settings.MEDIA_URL):
    # Initialization
    super(FileStorage, self).__init__(location, base_url)
 
  # Override the _save method
  def _save(self, name, content):
    # file extension
    ext = (name)[1]
    # Document directory
    d = (name)
    # Define filename, source filename, avoid system-defined random string appending, so avoid not using the name field
    end = utils.find_last(str(content), ".")
    filename = ""
    if end != -1:
      filename = str(content)[:end]
    # Define filename, year, month, day, hour, minute and second random numbers
    fn = ("%Y%m%d%H%M%S")
    fn = fn + "_%d" % (0,100)
    # Rewrite synthetic filenames
    name = (d, filename + fn + ext)
    # Call parent class methods
    return super(FileStorage, self)._save(name, content)

# Get the position of the last occurrence of the specified character in the string
def find_last(string,str):
  last_position=-1
  while True:
    position=(str,last_position+1)
    if position==-1:
      return last_position
    last_position=position

In this way, the final uploaded file name for the original file name plus the year, month, day, hour and second plus 0-100 random number to save, the effect is as follows:

Above this Django delete upload_to file steps is all I have shared with you, I hope to give you a reference, and I hope you support me more.