Django - Serving Media/Admin files in production with Apache/Webfaction - python

As it stands my STATIC files are served without issue using the configuration below.
In my settings.py:
MEDIA_ROOT = '/home/chronic88/webapps/media_media/'
MEDIA_URL = '/media/'
STATIC_ROOT = '/home/chronic88/webapps/static_media/'
STATIC_URL = '/static/'
static_media and media_media are both applications served by apache.
I can upload files via the admin and they show up inside the folder media_media, but they won't display on their pages. When I check the file paths in the page source they seem correct mydomain.com/media/image.png but they simply won't display. So, it seems the link is there but there is some problem communicating between apache and django that I can't put my finger on.
And my main urls.py:
admin.autodiscover()
urlpatterns = patterns('',
url(r'^', include('polls.urls', namespace="polls")),
url(r'^admin/', include(admin.site.urls)),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
This is the urls.py I'm using in prodution that works. I tried it without the last line in production but it gives the same result (files are uploaded but not displayable).
What am I missing?

If you configured your Apache to serve the static files from the respective root folders, you also have to run manage.py collectstatic (see docs).
To test static and media files I usually have this in my urls.py:
urlpatterns += patterns('',
(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT, 'show_indexes': True}),
)

Related

Django is not serving static and media files in development but it is serving in production

I am using windows 10 as OS in development environment and Ubuntu 18.04 (AWS) in production. I deployed my application recently (15 days) but now when I see the django is no more serving media and static files in the development server while it is running and serving perfectly in the production server (with DEBUG=True in both the servers). I am using Nginx server with gunicorn at the production server.
I have tried almost every answer in the StackOverflow to counter this issue but it is not working.
settings.py:
# MEDIA:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
...
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
STATIC_URL = '/static/'
# STATICFILES_DIRS = ('static', )
#STATICFILES_DIRS = (os.path.join('static'), )
main_project/urls.py:
from django.contrib import admin
from django.urls import path, include
from django.conf import settings # new
from django.conf.urls.static import static # new
urlpatterns = [
path('', include('stock_management.urls', namespace='stock_management')),
path('auth/', include('django.contrib.auth.urls')),
path('admin/', admin.site.urls),
]
# if settings.DEBUG: # new
# urlpatterns += static(settings.STATIC_URL,
# document_root=settings.STATIC_ROOT)
# urlpatterns += static(settings.MEDIA_URL,
# document_root=settings.MEDIA_ROOT)
app/urls.py:
from django.urls import path, include
from .views import *
from django.conf import settings
app_name = 'stock_management'
urlpatterns = [
# Stock:
path('', stock_list, name='homepage'),
path('stock/', stock_list, name='stock_list'),
path('stock/add', stock_create_view, name='add_stock'),
path('stock/<pk>/edit', stock_edit, name='stock_edit'),
# Item:
path('items/', item_list, name='item_list'),
path('item/<pk>/edit', item_edit, name='item_edit'),
path('item/<pk>/delete', item_delete, name='item_delete'),
# API
path('api/items', item_list_API, name='item_list_API'),
# Gallery:
path('items/gallery', item_gallery, name='item_gallery'),
]
# if settings.DEBUG:
# # test mode
# from django.conf.urls.static import static
# urlpatterns += static(settings.STATIC_URL,
# document_root=settings.STATIC_ROOT)
# urlpatterns += static(settings.MEDIA_URL,
# document_root=settings.MEDIA_ROOT)
I want a solution so that django can serve static and media files to my localhost also and at the same time when I commit any changes, it does not disturb the production enviornment.
EDIT:
I have uncommented the settings.DEBUG condition from both the urls.py files and now it is serving the media files but not static files in the local server.
if settings.DEBUG:
# test mode
from django.conf.urls.static import static
urlpatterns += static(settings.STATIC_URL,
document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
if settings.DEBUG: # new
urlpatterns += static(settings.STATIC_URL,
document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
After much effort, I think I have found the answer.
In the development server the following configurations works:
STATIC_ROOT = ''
STATIC_URL = '/static/'
STATICFILES_DIRS = ('static', )
While in production server with Nginx properly set up to serve the static files the following configuration is enough:
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
STATIC_URL = '/static/'
if you want to serve static files during development:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
this setting is the only thing you need in your setting file which i assume your STATIC_URL is defined as /static/ , you comment out those lines and it will work.
I took these lines from documentation. Hence you can use seperate settings files for production and development of django also. so one will have DEBUG=True while the other one is defined False, which I think that is the reason that your problem is occurs.
ps: according to your BASE_DIR setting. add two lines to your development settings in settings.py file
STATIC_ROOT = os.path.join(BASE_DIR, 'static_cdn')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
and for the urls.py I use these lines
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

can't get media files in heroku

I deployed mu project in heroku successfully.
The only problem is that I can't find media files on heroku.
When I type .../media/pic1.png locally , I get the picture in the browser.
But, in heroku,, that gives
Page not found (404)
Request Method: GET
Request URL:
...../media/pic1.png
Raised by: django.views.static.serve
Path ...../media/pic1.png doesn't exist
settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
project/urls.py
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^admin_platform/', include('admin_platform.urls')),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Your setting.py should look something like this:-
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')#by doing this there will be media folder in your main directory.
And in your url.py your code should be like this:-
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^admin_platform/', include('admin_platform.urls')),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)#this will help to access your media folder.
Hope this help in your project. :-)

URL for Static files in Django Project

I am running Django project at suburl like www.example.com/django . Everything is working fine but my static files are not working on this suburl since they the url they are taking is main like www.example.com/static/path_to_files but it should take the url as www.example.com/django/static/path_to_files.
This can be the case for other urls too because I think whenever I use any url for any link it must take the hostname with the suburl like www.example.com/django instead of www.example.com .
you can also see this question of mine for more information about server configuration files.
In settings.py try:
STATIC_URL = '/django/static/'
More information here: https://docs.djangoproject.com/en/dev/howto/static-files/
You can serve them manually during development by adding the lines to urls.py:
urlpatterns = patterns('',
# Media files
url(r'^media/(?P<path>.*)$',
'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT, 'show_indexes': True}
),
# Static files
url(r'^static/(?P<path>.*)$',
'django.views.static.serve',
{'document_root': settings.STATIC_ROOT, 'show_indexes': True}
),
)
Don't use this in production, and read the doc, its well explained.
Define MEDIA_URL and STATIC_URL in settings.py
MEDIA_URL = /django/media
STATIC_URL = /django/static
Then prepend this variable while defining url in templates:
media
<img src="{{ STATIC_URL }}/path_to_static_file" />
Now you can use these variables wherever you want to create urls.

Django python - Module not found

I am a newbie so I might have done something stupid. running python 3.3 and Django 1.6.2.
When I run the local server via command line, this is the error I receive "P/1.1 404 1712" and error on the browser is "module not found" and the exception location direct me urls.py line 22;
document_root=settings.STATIC_ROOT)
this is a part of urls.py:
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls import static
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
url(r'^$', 'signups.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
)
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL,
document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
This is how my settings.py looks:
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/
STATIC_URL = '/whattheheck/static/'
# Template location
TEMPLATE_DIRS = {
os.path.join(os.path.dirname(BASE_DIR), "whattheheck", "static", "templates"),
}
if DEBUG:
MEDIA_URL = '/whattheheck/media/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "whattheheck", "static", "static-only")
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "whattheheck", "static", "media")
STATICFLIES_DIRS = (
os.path.join(os.path.dirname(BASE_DIR), "whattheheck", "static", "static")
)
Can someone help please?
You forgot one static in the import statement, see the documentation:
from django.conf.urls.static import static
# ^^^^^^ this one
Right now, it tries to use the static module as a function but obviously, it does not work. The error 'module' object is not callable is raised when you are trying to use a module object (for example os, sys or any third-party) as a callable (with a __call__ method).

Django MEDIA_URL and MEDIA_ROOT

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.
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
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)
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
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>
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.
(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')),
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',
],
},
},
]
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)
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/'
This if for Django 1.10:
if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
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}))
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
]
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.
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 ;)
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)
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)
)
Add this code in settings.py
urlpatterns = [
....
....
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Categories