Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting username in ImageField upload_to path

I would like to include the username in my upload_to directory path for when a user uploads an image. Here is what I currently have --

#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',)

How would I get the USERNAME in the model to be able to set the upload_to path?

like image 987
David542 Avatar asked Jun 14 '11 21:06

David542


1 Answers

upload_to can be a callable instead of a string, in which case it will be passed the current instance and the filename -- see the documentation. Something like this should work (instance.user.user because instance.user is the UserProfile, so instance.user.user is the 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)
like image 126
Ismail Badawi Avatar answered Oct 10 '22 16:10

Ismail Badawi