I'm trying to pass a custom upload_to function to my models imageField but I'd like to define the function as a model function....is that possible?
class MyModel(models.Model):
...
image = models.ImageField(upload_to=self.get_image_path)
...
def get_image_path(self, filename):
...
return image_path
Now i know i can't reference it by 'self' since self doesn't exist at that point...is there a way to do this? If not - where is the best place to define that function?
So Just remove "@classmethod" and Secator's code will work.
class MyModel(models.Model):
# Need to be defined before the field
def get_image_path(self, filename):
# 'self' will work, because Django is explicitly passing it.
return filename
image = models.ImageField(upload_to=get_image_path)
You can use staticmethod decorator to define the upload_to
inside of a class (as a static method). Hovever it has no real benefit over typical solution, which is defining the get_image_path before class definition like here).
class MyModel(models.Model):
# Need to be defined before the field
@classmethod
def get_image_path(cls, filename):
# 'self' will work, because Django is explicitly passing it.
return filename
image = models.ImageField(upload_to=get_image_path)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With