Skip to content

Instantly share code, notes, and snippets.

@hansek
Created March 24, 2017 12:15
Show Gist options
  • Save hansek/296514ba784c1f93186472ef574d39a4 to your computer and use it in GitHub Desktop.
Save hansek/296514ba784c1f93186472ef574d39a4 to your computer and use it in GitHub Desktop.
Allow to define abstract class and don't hardcode upload_to path for each FileField
from django.db import models
class BaseFileField(models.FileField):
"""
Allow to define abstract class and don't hardcode upload_to path for each FileField
class BaseFile(models.Model):
name = models.CharField(
max_length=200,
blank = True
)
file = BaseFileField(
blank=True
)
class Meta:
abstract = True
class Tag(BaseFile):
@staticmethod
def get_upload_to(obj, filename, field):
return '{}/{}'.format(
obj._meta.app_label,
filename
)
...
"""
def generate_filename(self, instance, filename):
if hasattr(instance, 'get_upload_to'):
upload_to = instance.get_upload_to(instance, filename, field=self)
filename = self.storage.generate_filename(upload_to)
else:
filename = super().generate_filename(instance, filename)
return filename
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment