本文介绍了Django ImageField传递一个可以上传到upload_to的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将自定义的upload_to函数传递给我的模型imageField,但我想将函数定义为模型函数....是可能的吗?
$ _ code class MyModel(models.Model):
...
image = models.ImageField(upload_to = self.get_image_path)
...
def get_image_path(self,filename):
...
return image_path
现在我知道我不能用'self'来引用它,因为在这一点上自己不存在...有没有办法呢?如果没有,那么定义该函数的最佳位置在哪里?
解决方案
所以只需删除@classmethod,Secator的代码将会工作
class MyModel(models.Model):
#需要在字段前定义
def get_image_path(self,filename):
#'self'将工作,因为Django明确地传递它。
返回文件名
image = models.ImageField(upload_to = get_image_path)
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)
这篇关于Django ImageField传递一个可以上传到upload_to的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!