I\'m trying to upload an image via the Django admin and then view that image either in a page on the frontend or just via a URL.
Note this is all on my local machine
Do I need to setup specific URLconf patters for uploaded media?
Yes. For development, it's as easy as adding this to your URLconf:
if settings.DEBUG:
urlpatterns += patterns('django.views.static',
(r'media/(?P<path>.*)', 'serve', {'document_root': settings.MEDIA_ROOT}),
)
However, for production, you'll want to serve the media using Apache, lighttpd, nginx, or your preferred web server.
This if for Django 1.10:
if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Please read the official Django DOC carefully and you will find the most fit answer.
The best and easist way to solve this is like below.
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns('',
# ... the rest of your URLconf goes here ...
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Here are the changes I had to make to deliver PDFs for the django-publications app, using Django 1.10.6:
Used the same definitions for media directories as you, in settings.py
:
MEDIA_ROOT = '/home/user/mysite/media/'
MEDIA_URL = '/media/'
As provided by @thisisashwanipandey, in the project's main urls.py
:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
and a modification of the answer provided by @r-allela, in settings.py
:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
# ... the rest of your context_processors goes here ...
'django.template.context_processors.media',
],
},
},
]
Another problem you are likely to face after setting up all your URLconf patterns is that the variable {{ MEDIA_URL }}
won't work in your templates. To fix this,in your settings.py, make sure you add
django.core.context_processors.media
in your TEMPLATE_CONTEXT_PROCESSORS
.
Following the steps mentioned above for =>3.0 for Debug mode
urlpatterns = [
...
]
+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
And also the part that caught me out, the above static URL only worked in my main project urls.py file. I was first attempting to add to my app, and wondering why I couldn't see the images.
Lastly make sure you set the following:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'