[Answered ]-Saving an image into user model

1๐Ÿ‘

โœ…

You need to configure your settings to serve static media properly when using a local environment.

Add this to your settings.py

DEBUG = True

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(__file__))

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
)
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles/')
STATIC_URL = '/static/'

MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'

Add this to your ROOT urls.py

from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf import settings
from django.conf.urls.static import static


if settings.DEBUG:
    urlpatterns += staticfiles_urlpatterns()
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
๐Ÿ‘คHybrid

1๐Ÿ‘

I dont know how your MEDIA_URL looks like but the media settings should look like something like this:

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, "media")

and no, you do not save media files under templates folder. this does not make any sense. templates should have html files, static should have static files (css, js, static images) and media user uploaded files.

this way, if someone joins your project or your project gets bigger, you dont end up in chaos/misleading folder names, otherwise it really hurts, believe me

For 404 issue:

you need change your main urls.py in root to include this:

if settings.DEBUG:
    urlpatterns += patterns('',
       url(r'^media/(?P<path>.*)$', 'django.views.static.serve',
       {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
    url(r'', include('django.contrib.staticfiles.urls')),
)
๐Ÿ‘คdoniyor

Leave a comment