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.
My settings are as follows:
MEDIA_ROOT = '/home/dan/mysite/media/'
MEDIA_URL = '/media/'
I have set the upload_to parameter to 'images' and the file has been correctly uploaded to the directory:
'/home/dan/mysite/media/images/myimage.png'
However, when I try to access the image at the following URL:
http://127.0.0.1:8000/media/images/myimage.png
I get a 404 error.
Do I need to setup specific URLconf patters for uploaded media?
Any advice appreciated.
Thanks.
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
:As provided by @thisisashwanipandey, in the project's main
urls.py
:and a modification of the answer provided by @r-allela, in
settings.py
: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.
UPDATE for Django >= 1.7
Per Django 2.1 documentation: Serving files uploaded by a user during development
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
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 andDEBUG = False
Yes. For development, it's as easy as adding this to your URLconf:
However, for production, you'll want to serve the media using Apache, lighttpd, nginx, or your preferred web server.
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 addin your
TEMPLATE_CONTEXT_PROCESSORS
.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:
I know that it is late, but just to help those who visit this link because of the same problem ;)