Login

Automatic Folder FileField

Author:
depaolim
Posted:
May 20, 2014
Language:
Python
Version:
1.6
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. Template tag - list punctuation for a list of items by shapiromatron 2 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 9 months, 4 weeks ago
  5. Help text hyperlinks by sa2812 10 months, 3 weeks ago

Comments

Please login first before commenting.