Make upload_to path of ImageField contain a CharField value of a field in the same model

Is it possible to define the upload_to path of an ImageField based on a CharField in the same model? For example:

class Profile(models.Model):

	def make_image_path(pathfolder):
		image_path = f"users/{pathfolder}/"
		return image_path
		
	username = models.CharField(max_length=50, unique=True)
	photo = models.ImageField(upload_to=make_image_path(username))

This currently works except result is users/<django.db.models.fields.CharField>/picture.jpeg

How can I make it show the username instead of <django.db.models.fields.CharField>.

Hi,

You’re using upload_to incorrectly.

Because of the way Python works, the value of upload_to is the return value of the function make_image_path(). What you want is for upload_to to be an actual function object.

There’s an example of using a function for upload_to in Django’s documentation: Model field reference | Django documentation | Django (look for the code example that defines user_directory_path a few paragraphs down).

I hope that helps!

Thank you, this works.