无法设置ImageField的url属性 [英] Can't set ImageField url attribute
问题描述
我想更改ImageField的属性,但是不断出现无法设置属性"错误.
I want to change my ImageField's attribute, however I'm constantly getting the Can't set attribute error.
我的模特是
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文件,其名称是一个时间值.然后到达Societys文件夹,我想重命名该文件.所以,我的fix_avatar只是在保存社团后将tmp文件的内容移动到society_(society_id)文件夹中.到目前为止,一切都很好.但是,我所在社区的ImageField仍然保存以前创建的文件夹.为了更改其值,我发现我可以使用干净的方法.(从此
I want to save my society directories as society_society_id. But normally, I can't assign any id before the model is saved. So i'm creating a tmp file whose name is a time value.Then to reach societies folder, I want to rename this file. So, my fix_avatar simply moves the tmp file's content to society_(society_id) folder after the society is saved. So far so good everything works well. However, my society's ImageField still holds the previously created folder. In order to change it's value, I found that i can use clean method.(from this SO question) But still i'm getting the same result, the path doesn't change, and gives the "can't set attribute" response.
任何想法??
推荐答案
不确定,由于提出了此问题,因此在Django中是否进行了更改.关于此操作的故障单仍然存在: https://code.djangoproject.com/ticket/15590
Not sure, if this was ever changed in Django since this question was asked. A ticket about this not being possible still exists: https://code.djangoproject.com/ticket/15590
但是,您实际上可以通过执行以下操作来更改路径:
However, you actually can change the path by doing it like this:
self.avatar = 'uploads/example/path/'
工作还做什么?
self.avatar.name = 'uploads/example/path/'
它为我们工作了好几次.
It has worked for us in several occasions.
这篇关于无法设置ImageField的url属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!