Retrieving username in ImageField upload_to path

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

#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 can I get USERNAME in the model to set the upload_to path?

+8
django django-models django-forms
source share
2 answers

upload_to can be called instead of a string, in which case the current instance and file name will be passed to it - see the documentation. Something like this should work ( instance.user.user , because instance.user is UserProfile , so instance.user.user is 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) 
+19
source share

The answer of Ismail Badawi is completely correct. You can also use the new string formatting and the lambda function.

New line formatting:

 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) 

Newline formatting and lambda function:

  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) 
0
source share

All Articles