Question

I hope someone could point me into the right direction.

The default Django FileSystemStorage function get_available_name returns just the name which is then stored in the db for the corresponding FileField.

The original get_available name look like this:

def get_available_name(self, name):

    dir_name, file_name = os.path.split(name)
    file_root, file_ext = os.path.splitext(file_name)
    count = itertools.count(1)
    while self.exists(name):
        name = os.path.join(dir_name, "%s_%s%s" % (file_root, count.next(), file_ext))

    return name

HOw could I possibly return count too. I tried to return a tuple like (name, count) and tried to fix the corresponding save method which are executed after get_available_name, but had no success in grabbing count. Background is that a got a file class which I save in view like this:

class DataFile(models.Model):
    title=models.CharField(max_length=255, unique=False, blank=False)
    file=models.FileField(max_length=255, blank=False, storage=fs, upload_to=get_path)

The view:

def save_uploaded_datafile(request):
   ### get request.FILES and save it
   f=DataFile()
   f.file=request.FILES['DataFile']
   f.title=f.file.name
   f.save()

How could I possibly return count from get_available_name from saving into the view for further processing? Any help is kindly appreciated. Thx!

PS: The posted code wont run, its more like pseudo code, but I hope you get the idea.

Was it helpful?

Solution

You could just check the filename that is returned by f.save():

file_name = f.save()
count = None
if file_name not f.title:
    file_root, file_ext = os.path.splitext(file_name)
    my_root, my_ext = os.path.splittext(f.title)
    # Add one to the length of my_root to capture the '_'
    root_length = len(my_root)+1
    count = int(file_root[root_length:])

This is a bit more expensive than finding a way of passing the count back, but it should do the trick.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top