5

I know that you can use the upload_to parameter to pass a callable function to dynamically alter a FileFied/ImageField, etc. in a Django model.

The function called by upload_to is passed 2 variables, the instance of the non-saved-in-the-database file (instance) and the filename of said instance (filename).

If I'm using an ImageField in a model along with other (Char, etc.) fields, is it possible to get the values from those fields into that same callable function.

for instance.

class Badge(models.Model):

  def format_badge_name(instance, filename):
    _filetype = os.path.splitext(filename)[1]
    _category = 'foo'
    _name = os.path.splitext(filename)[0]
    _filename = "%s-%s-%s%s" % (_category, _name, 'private', _filetype)

    return "badges/%s" % _filename

  name = models.CharField(max_length=16, help_text="Name for Badge")
  file = models.ImageField(upload_to=format_badge_name)

Is it possible to pass the values from name (self.name?) into format_badge_name?

jduncan
  • 677
  • 2
  • 12
  • 22

1 Answers1

12

The instance variable is the Badge() instance. You could access it's properties as usual

def format_badge_name(instance, filename):
    instance.name
    instance.file
    ...

You could name the instance 'self', and it might be easier to be understood:

def format_badge_name(self, filename):
    self.name
    self.file
    ...
okm
  • 23,575
  • 5
  • 83
  • 90