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?

1
  • What are you attempting to do? Commented May 30, 2012 at 3:36

1 Answer 1

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
    ...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.