Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django store user image in model

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.

like image 512
dragoon Avatar asked Nov 18 '11 22:11

dragoon


People also ask

How do I store images in Django?

In Django, a default database is automatically created for you. All you have to do is add the tables called models. The upload_to tells Django to store the photo in a directory called pics under the media directory. The list_display list tells Django admin to display its contents in the admin dashboard.

How do I add an image to a Django project?

In django we can deal with the images with the help of model field which is ImageField . In this article, we have created the app image_app in a sample project named image_upload. The very first step is to add below code in the settings.py file. MEDIA_ROOT is for server path to store files in the computer.


1 Answers

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

like image 107
j_syk Avatar answered Sep 20 '22 12:09

j_syk