我想在用户上传图片时在upload_to目录路径中包含用户名。这是我目前的情况 -
#model
class Avatar(models.Model):
avatar = models.ImageField(upload_to='images/%s' %(USERNAME) )
user = models.ForeignKey(UserProfile)
#form
class ProfilePictureForm(ModelForm):
class Meta:
model = Avatar
fields = ('avatar',)
如何让模型中的USERNAME
能够设置upload_to路径?
答案 0 :(得分:19)
upload_to
可以是可调用的而不是字符串,在这种情况下,它将传递当前实例和文件名 - 请参阅documentation。这样的事情应该有效(instance.user.user
因为instance.user
是UserProfile
,所以instance.user.user
是User
。
def upload_to(instance, filename):
return 'images/%s/%s' % (instance.user.user.username, filename)
class Avatar(models.Model):
avatar = models.ImageField(upload_to=upload_to)
user = models.ForeignKey(UserProfile)
答案 1 :(得分:0)
Ismail Badawi的回答是完全正确的。您还可以使用新的字符串格式和lambda函数。
新字符串格式:
def upload_to(instance, filename):
return 'images/{username}/{filename}'.format(
username=instance.user.user.username, filename=filename)
class Avatar(models.Model):
avatar = models.ImageField(upload_to=upload_to)
user = models.ForeignKey(UserProfile)
新字符串格式和lambda函数:
path = lambda instance, filename: 'images/{username}/{filename}'.format(
username=instance.user.user.username, filename=filename)
class Avatar(models.Model):
avatar = models.ImageField(upload_to=path)
user = models.ForeignKey(UserProfile)