__friendly_path.py 847 Bytes
Newer Older
1
2
3
4
from django.conf import settings
from django.utils.deconstruct import deconstructible
import os

Florent Chehab's avatar
Florent Chehab committed
5

6
7
@deconstructible
class friendly_path(object):
Florent Chehab's avatar
Florent Chehab committed
8
9
10
11
    """
    class to generate file path with filenames
    according to one of the model attribute
    """
Florent Chehab's avatar
linting  
Florent Chehab committed
12

13
14
15
16
17
18
19
20
    def __init__(self, rel_path, attribute_distinction):
        self.rel_path = rel_path
        self.attr = attribute_distinction

    def __call__(self, instance, filename):
        ext = filename.split('.')[-1]
        i = 0
        while True:
Florent Chehab's avatar
Florent Chehab committed
21
22
23
24
            filename = '{}_{}.{}'.format(
                getattr(instance, self.attr), str(i), ext)
            path_and_fn = os.path.join(
                settings.MEDIA_ROOT, self.rel_path, filename)
25
26
27
28
            if not os.path.isfile(path_and_fn):
                break
            i += 1

Florent Chehab's avatar
linting  
Florent Chehab committed
29
        return os.path.join(self.rel_path, filename)