32

I'm trying to create a field in a model, that should store an image for a registered user. This image should be renamed and stored in a separate user directory like media/users/10/photo.jpeg.

I've searched a lot, but still can't find how to do it cleanly and correctly. It seems to me that many sites require the same functionality and this should be in django docs, but it is not.

dragoon
  • 5,601
  • 5
  • 37
  • 55

3 Answers3

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
  • 6,511
  • 2
  • 39
  • 56
  • Cool, this actually does save file to the correct location, but when I use in template ``{{ user.profile_image }}`` it for some reason gives ``/users/users/40/photo.png`` instead of ``/media/users/40/photo.png`` – dragoon Nov 19 '11 at 14:58
  • 4
    models.ForeignKey(User, unique=True) should be models.OneToOneField(User) – vinyll Sep 18 '12 at 11:36
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/

juliomalegria
  • 24,229
  • 14
  • 73
  • 89
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.

gdlmx
  • 6,479
  • 1
  • 21
  • 39
Brandon Taylor
  • 33,823
  • 15
  • 104
  • 144
  • 3
    I'm sorry, but the question is not about the model, it's about how to store images. – dragoon Nov 18 '11 at 22:35
  • 1
    You can create a dynamic upload path for any FileField or Image field. Just add a function to your model that returns the path for upload_to. You can find an example in the Django docs at: https://docs.djangoproject.com/en/1.3/ref/models/fields/#filefield – Brandon Taylor Nov 18 '11 at 22:43
  • 1
    @ShamsulArefinSajib This answer is 7 years old. The updated link is: https://docs.djangoproject.com/en/2.1/ref/models/fields/#imagefield – Brandon Taylor Aug 11 '18 at 18:05