[Django]-Django store user image in model

57👍

You want to use the “upload_to” option on an ImageField

#models.py
import os

def get_image_path(instance, filename):
    return os.path.join('photos', str(instance.id), filename)

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    profile_image = ImageField(upload_to=get_image_path, blank=True, null=True)

This is code directly from a project of mine. The uploaded image goes to /MEDIA_ROOT/photos/<user_id>/filename

For what you want, just change the ‘photos’ string to ‘users’ in def get_image_path

Here is the small bit about it in the docs, under FileField details

👤j_syk

2👍

I suggest you to look into django-photologue. Its a django app with all image managment, uploading and storing already done!

More about at: http://code.google.com/p/django-photologue/

1👍

You’ll need to make a model that has a foreign key to the User model, where you can have an image field for the User. I would not recommend modifying the User model itself.

Leave a comment