Django ImageField passing call for upload_to

I am trying to pass a custom upload_to function to my imageField models, but I would like to define the function as a model function .... is this 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 that I can not refer to it as "I", since I myself do not exist at this moment ... is there a way to do this? If not, where is the best place to define this function?

+4
source share
2 answers

So just remove the "@classmethod" and the Secator 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) 
+8
source

You can use staticmethod decorator to define upload_to inside the class (as a static method). Hovever has no real benefit from a typical solution that defines the path get_image_path to the class definition as here ).

 class MyModel(models.Model): # Need to be defined before the field @classmethod 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) 
+2
source

Source: https://habr.com/ru/post/1394114/


All Articles