Skip to content

Instantly share code, notes, and snippets.

@hansek hansek/models.py

Created Mar 24, 2017
Embed
What would you like to do?
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
You can’t perform that action at this time.