我想更改 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 文件,其名称是时间值。然后为了到达 Society 文件夹,我想重命名该文件。因此,我的 fix_avatar 只是在保存协会后将 tmp 文件的内容移动到 Society_(society_id) 文件夹。到目前为止一切都很好。但是,我的协会的 ImageField 仍然保存着之前创建的文件夹。为了改变它的值,我发现我可以使用 clean 方法。(来自此 SO question )但我仍然得到相同的结果,路径没有改变,并给出“无法设置属性”回复。
有什么想法吗?
最佳答案
不确定,自从提出这个问题以来,Django 中是否有过更改。关于此不可能的票证仍然存在:https://code.djangoproject.com/ticket/15590
但是,您实际上可以通过这样做来更改路径:
self.avatar = 'uploads/example/path/'
这项工作还做什么:
self.avatar.name = 'uploads/example/path/'
它曾多次为我们提供帮助。
关于django - 无法设置 ImageField url 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5189114/