Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - passing extra arguments into upload_to callable function

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?

like image 422
jduncan Avatar asked May 30 '12 03:05

jduncan


1 Answers

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
    ...
like image 59
okm Avatar answered Oct 31 '22 11:10

okm