【问题标题】:sorl-thumbnail ImageField dynamic upload_to pathsorl-thumbnail ImageField动态upload_to路径
【发布时间】:2012-03-01 03:58:55
【问题描述】:

我知道在 django ImageFields 和 FileFields 中有一种动态上传路径的方法,即在字段中传递一个 upload_to=callable,但是有没有办法通过 sorl-thumbnail ImageField 来实现呢?

这是我的 model.py,我得到一个未定义的上传路径!

class Brand(models.Model):
    title = models.CharField(max_length=255, null=True, blank=True)
    photo = sorl.thumbnail.ImageField(upload_to=upload_path)
    external = models.BooleanField(_('External Brand? ("Key Account")?'))

    def upload_path(self):
        return u'%s' % self.title

【问题讨论】:

    标签: django django-models sorl-thumbnail


    【解决方案1】:

    this related SO question

    Sorl-thumbnail 对upload_to 没有任何特殊作用。它只是通过从 Django 的 FileField 继承来处理传递的参数,因此任何与标准 FileFieldImageField 一起使用的东西都可以与 sorl-thumbnail 的 ImageField 一起使用。

    我认为您的问题是在模型上定义方法。我自己见过或做过的每一个实现都有模型之外的方法。 Django 自动将实例传递给方法,这就是您访问模型数据的方式——而不是通过self

    【讨论】:

      【解决方案2】:

      我将此回调与 sorl 一起使用:

      def get_image_path(instance, filename):
          """
          puts image in MEDIA_ROOT/photos/instance_id/file
          """
          return os.path.join('photos', str(instance.id), filename)
      
      class Brand(models.Model):
          ...
          photo = sorl.thumbnail.ImageField(upload_to=get_image_path)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-22
        • 2016-05-09
        • 2011-05-20
        • 1970-01-01
        • 1970-01-01
        • 2011-02-08
        相关资源
        最近更新 更多