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
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.