Django - loading a default static image into an ImageField file

These are my models.py:

def get_profileImage_file_path(instance, filename): return os.path.join('%s/uploadedPhotos/profileImages' % instance.user_id, filename) class UserExtended(models.Model): user = models.OneToOneField(User) profileImage = models.ImageField(upload_to=get_profileImage_file_path, default='/static/images/myProfileIcon.png') 

Now I want the default image (which is in my static folder) to be saved to the path specified in

 get_profileImage_file_path 

function. In my settings.py, I defined media_root and media_URL as:

 MEDIA_ROOT = '/home/username/Documents/aSa/userPhotos' MEDIA_URL = '/media/' 

For some reason, when I pass the user object in the template and in the template, if I do this:

 <img class='profilePic' src="{{ user.userextended.profileImage.url }}" height='120px' alt="" /> 

No image appears, and when I open the "check item" section in chrome, it gives a 404 error:

 GET http://127.0.0.1:8000/home/username/Documents/djcode/aS/aSa/static/images/myProfileIcon.png 404 (NOT FOUND) 

although this is the correct path to the file. (I’m also not sure why it gives the whole path to the file, should it not just start with / static /? Even when I "look through the source", the whole URL is there.) How can I make the default image which is located in a static folder, is loaded into the path specified in

 get_profileImage_file_path 

function?

+6
source share
1 answer

In general, we use the following configuration for media:

 BASE_DIR = dirname(dirname(abspath(__file__))) MEDIA_ROOT_DIR = 'media' MEDIA_ROOT = normpath(join(BASE_DIR, MEDIA_ROOT_DIR)) MEDIA_URL = '/media/' 

For development purposes:

 DEBUG = True 

And in urls.py add the following:

 from django.conf import settings from django.conf.urls.static import static if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) 

Download the image again and check the image, it should work now.

+2
source

Source: https://habr.com/ru/post/972066/


All Articles