368π
UPDATE for Django >= 1.7
Per Django 2.1 documentation: Serving files uploaded by a user during development
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)
You no longer need if settings.DEBUG
as Django will handle ensuring this is only used in Debug mode.
ORIGINAL answer for Django <= 1.6
Try putting this into your urls.py
from django.conf import settings
# ... your normal urlpatterns here
if settings.DEBUG:
# static files (images, css, javascript, etc.)
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT}))
With this you can serve the static media from Django when DEBUG = True
(when you run on local computer) but you can let your web server configuration serve static media when you go to production and DEBUG = False
116π
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)
- [Django]-Django-Forms with json fields
- [Django]-Why does django run everything twice?
- [Django]-Django Generic Views using decorator login_required
77π
For Django 1.9, you need to add the following code as per the documentation :
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)
For more info, you can refer here : https://docs.djangoproject.com/en/1.9/howto/static-files/#serving-files-uploaded-by-a-user-during-development
- [Django]-Malformed Packet: Django admin nested form can't submit, connection was reset
- [Django]-How does django handle multiple memcached servers?
- [Django]-Jquery template tags conflict with Django template!
39π
Here What i did in Django 2.0. Set First MEDIA_ROOT an MEDIA_URL in setting.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'data/') # 'data' is my media folder
MEDIA_URL = '/media/'
Then Enable the media
context_processors
in TEMPLATE_CONTEXT_PROCESSORS
by adding
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
#here add your context Processors
'django.template.context_processors.media',
],
},
},
]
Your media context processor
is enabled, Now every RequestContext
will contain a variable MEDIA_URL
.
Now you can access this in your template_name.html
<p><img src="{{ MEDIA_URL }}/image_001.jpeg"/></p>
- [Django]-How do I POST with jQuery/Ajax in Django?
- [Django]-Suppress "?next=blah" behavior in django's login_required decorator
- [Django]-Django set default form values
24π
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.
- [Django]-Get list item dynamically in django templates
- [Django]-Negating a boolean in Django template
- [Django]-Django CMS fails to synch db or migrate
8π
If youβr using python 3.0+ then configure your project as below
Setting
STATIC_DIR = BASE_DIR / 'static'
MEDIA_DIR = BASE_DIR / 'media'
MEDIA_ROOT = MEDIA_DIR
MEDIA_URL = '/media/'
Main Urls
from django.conf import settings
from django.conf.urls.static import static
urlspatterns=[
........
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
- [Django]-How to test "render to template" functions in django? (TDD)
- [Django]-How to use Django ImageField, and why use it at all?
- [Django]-Django filter JSONField list of dicts
6π
(at least) for Django 1.8:
If you use
if settings.DEBUG:
urlpatterns.append(url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}))
as described above, make sure that no βcatch allβ url pattern, directing to a default view, comes before that in urlpatterns = []. As .append will put the added scheme to the end of the list, it will of course only be tested if no previous url pattern matches. You can avoid that by using something like this where the βcatch allβ url pattern is added at the very end, independent from the if statement:
if settings.DEBUG:
urlpatterns.append(url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}))
urlpatterns.append(url(r'$', 'views.home', name='home')),
- [Django]-Group by Foreign Key and show related items β Django
- [Django]-Troubleshooting Site Slowness on a Nginx + Gunicorn + Django Stack
- [Django]-Serializer call is showing an TypeError: Object of type 'ListSerializer' is not JSON serializable?
6π
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',
],
},
},
]
- [Django]-How to test auto_now_add in django
- [Django]-VueJS + Django Channels
- [Django]-How to test Django's UpdateView?
5π
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
.
- [Django]-How to access request body when using Django Rest Framework and avoid getting RawPostDataException
- [Django]-Unittest Django: Mock external API, what is proper way?
- [Django]-Django connection to postgres by docker-compose
5π
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/'
- [Django]-How to combine multiple QuerySets in Django?
- [Django]-What is reverse()?
- [Django]-'staticfiles' is not a valid tag library: Template library staticfiles not found
3π
This if for Django 1.10:
if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
- [Django]-Django β getting Error "Reverse for 'detail' with no arguments not found. 1 pattern(s) tried:" when using {% url "music:fav" %}
- [Django]-How to execute a Python script from the Django shell?
- [Django]-Laravel's dd() equivalent in django
2π
Adding to Micah Carrick answer for django 1.8:
if settings.DEBUG:
urlpatterns.append(url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}))
- [Django]-Logging in Django and gunicorn
- [Django]-Django β iterate number in for loop of a template
- [Django]-Sending HTML email in django
2π
This is what I did to achieve image rendering in DEBUG = False mode in Python 3.6 with Django 1.11
from django.views.static import serve
urlpatterns = [
url(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}),
# other paths
]
- [Django]-Django queryset filter β Q() | VS __in
- [Django]-CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true
- [Django]-Django: guidelines for speeding up template rendering performance
2π
On production environment Django does not load the media root automatically so that we can overcome that issue by adding following codes right after URL patterns:
urlpatterns = [
''''
your urls
''''
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
If you are using more than one app and if you are including app urls on main app url, just add this code(configuration) on main project URL.
- [Django]-Validators = [MinValueValidator] does not work in Django
- [Django]-How to use regex in django query
- [Django]-How to check Django version
1π
Your setting is all right. Some web servers require to specify the media and static folder files specifically. For example in pythonanywhere.com you have to go to the βWebβ section and add the url od the media folders and static folder. For example:
URL Directory
/static/ /home/Saidmamad/discoverthepamirs/static
/accounts/static/ /home/Saidmamad/discoverthepamirs/accounts/static
/media/ /home/Saidmamad/discoverthepamirs/discoverthepamirs/media
I know that it is late, but just to help those who visit this link because of the same problem π
- [Django]-Google Static Maps URL length limit
- [Django]-Switching to PostgreSQL fails loading datadump
- [Django]-Django storages: Import Error β no module named storages
1π
Add this code below to "settings.py" to access(open or display)uploaded files:
# "urls.py"
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)
- [Django]-In Django 1.4, do Form.has_changed() and Form.changed_data, which are undocumented, work as expected?
- [Django]-How to pass information using an HTTP redirect (in Django)
- [Django]-Django-nonrel + Django-registration problem: unexpected keyword argument 'uidb36' when resetting password
0π
For Django 3.0+ in development have the below in your main urls.py:
urlpatterns = [
# rest of your url paths here..
]
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) +
static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
)
- [Django]-Django: how to do calculation inside the template html page?
- [Django]-Convert Django Model object to dict with all of the fields intact
- [Django]-ValueError: The field admin.LogEntry.user was declared with a lazy reference
0π
Add this code in settings.py
urlpatterns = [
....
....
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
- [Django]-Django Rest Framework pagination extremely slow count
- [Django]-How to make an auto-filled and auto-incrementing field in django admin
- [Django]-When saving, how can you check if a field has changed?