2

我想更改 ImageField 的属性,但是我不断收到无法设置属性错误。

我的模型是

class Society(models.Model):
     name = models.CharField(max_length=200)
     slug = models.SlugField(unique=True)
     summary = models.TextField(blank=True,null=True)
     members = models.ManyToManyField(User,null=True,blank=True)
     gallery = models.ForeignKey(Gallery,null=True,blank=True)
     avatar = models.ImageField(upload_to=get_society_path)

     def save(self,*args,**kwargs):
          super(Society, self).save(*args,**kwargs)
          fix_avatar_path(self)

     def clean(self):
          if self.id:
               self.avatar.path = get_society_path(self,self.avatar.path)
               save_thumb(self.avatar.path)

我的辅助功能是:

def get_society_path(instance,filename):
     seperator_val = instance.id
     if seperator_val is None:
          seperator_val = get_time()
     return '%s/society_%s/%s' % (settings.UPLOAD_ROOT,seperator_val,time_to_name(filename))

def fix_avatar_path(instance):
     org_society_path = get_society_path(instance,instance.avatar.name)
     make_upload_dir(org_society_path)
     move(instance.avatar.path,org_society_path)
     os.rmdir(os.path.dirname(instance.avatar.path))
     instance.clean()

问题是 :

我想将我的社会目录保存为 Society_society_id。但通常,我不能在模型保存之前分配任何 id。所以我正在创建一个名称为时间值的 tmp 文件。然后要到达社团文件夹,我想重命名这个文件。因此,我的 fix_avatar 只是在保存社团后将 tmp 文件的内容移动到 social_(society_id) 文件夹。到目前为止一切都很好。但是,我社团的 ImageField 仍然保存着之前创建的文件夹。为了改变它的价值,我发现我可以使用干净的方法。(来自this SO question)但我仍然得到相同的结果,路径没有改变,并给出“无法设置属性”响应.

任何想法 ??

4

2 回答 2

3

不确定,自从提出这个问题以来,这是否在 Django 中发生了变化。关于这不可能的票仍然存在:https ://code.djangoproject.com/ticket/15590

但是,您实际上可以通过以下方式更改路径:

self.avatar = 'uploads/example/path/'

还有什么工作:

self.avatar.name = 'uploads/example/path/'

它曾多次为我们工作。

于 2013-05-04T05:57:43.300 回答
1

问题在这里:

self.avatar.path = get_society_path(self,self.avatar.path)

您不能更改 FileField/ImageField 实例中路径属性的值,它是只读的。在 Django 1.4 中有一个改变这个的提议

于 2011-04-05T21:42:30.487 回答