Login

Automatic Folder FileField

Author:
depaolim
Posted:
May 20, 2014
Language:
Python
Version:
1.6
Tags:
upload_to FileField
Score:
0 (after 0 ratings)

Your MEDIA_ROOT directories are a mess? FileField save on "upload_to" directories with old/strange/temporary names decided "on the fly" and never fixed down?

SmartFolderFileField is the solution! "upload_to" directory depends only on: app, model and field names. No mess, no ambiguities

Obviously, in case you need a real callable for a dynamic directory name: please use it! and leave apart FixedFolderFileField

Sample:

from django.db import models
from utilities_app.models import SmartFolderFileField

class SampleModel(models.Model):
    sample_char_field = models.CharField(max_length=50)
    sample_file_field = SmartFolderFileField()
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# ##############################################################################
# models.py
# ##############################################################################

import os
from django.db import models

class SmartFolderFileField(models.FileField):
    def get_fixed_folder_path(self, instance, filename):
        folder = "_".join([
            instance._meta.app_label,
            instance._meta.object_name,
            self.name])
        return os.path.join(folder, filename)

    def __init__(self, *args, **kwargs):
        assert not "upload_to" in kwargs
        kwargs["upload_to"] = self.get_fixed_folder_path
        super(SmartFolderFileField, self).__init__(*args, **kwargs)

# ##############################################################################
# tests.py
# ##############################################################################

from django.test import TestCase
from models import *

class TestSmartFolderFileField(TestCase):

    def test_directory_name(self):
        class DummyModel(models.Model):
            fixed = SmartFolderFileField()

        dm = DummyModel()
        self.assertEquals(
            dm.fixed.field.upload_to(dm, 'file_name'),
            os.path.join('utilities_app_DummyModel_fixed', 'file_name'))

More like this

  1. Use the primary key in FileField and ImageField filenames by exogen 6 years, 4 months ago
  2. FileField / ImageField with a delete checkbox by tomZ 7 years, 3 months ago
  3. Imagefield with variations by fivethreeo 6 years, 6 months ago
  4. Database file storage by powerfox 6 years, 1 month ago
  5. Updated FileField / ImageField with a delete checkbox by tomZ 6 years, 12 months ago

Comments

Please login first before commenting.