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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With