在ImageField upload_to路径中获取用户名

时间:2011-06-14 21:05:34

标签: django django-forms django-models

我想在用户上传图片时在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路径?

2 个答案:

答案 0 :(得分:19)

upload_to可以是可调用的而不是字符串,在这种情况下,它将传递当前实例和文件名 - 请参阅documentation。这样的事情应该有效(instance.user.user因为instance.userUserProfile,所以instance.user.userUser

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)