Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - uploading static image as default ImageField file

This is 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 save to the path given in the

get_profileImage_file_path

function. In my settings.py, I have 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:

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

No image shows up and when I open up the 'inspect element' section in chrome, it gives a 404 error saying:

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

even though that is the correct file path to the image. (I'm also not sure why it's giving the entire file path, isn't it just supposed to start from /static/? Even when I 'view source', the entire url is there.) How do I make it so that the default image which is located in the static folder uploads to the path provided in the

get_profileImage_file_path

function?

like image 260
SilentDev Avatar asked Jul 11 '14 05:07

SilentDev


1 Answers

In general we use the config as follows 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 set :

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)

Upload the image again and validate the Image, it should work now.

like image 121
Abhishek Agarwala Avatar answered Nov 05 '22 00:11

Abhishek Agarwala