Reputation: 1533
I deployed a website with django. it servs all static files but doesn't serve user-uploaded files.
this is my settings.py
and urls.py
:
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DEBUG = False
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticroot')
STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")]
MEDIA_URL = '/files/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'uploaded_files')
and the urls.py
:
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', Index.as_view(), name='index'),
]
In the pages, it prints user-uploaded files addresses correctly, but doesn't show them anf when I click on the links, it shows me 404 page. I use last version of nginx that I took from nginx repositories. the version 1.12. is it related to django or webserver(nginx+ gunicorn)? and how can I solve the problem?
Update
When I change the MEDIA_URL
and DEBUG
to True, for the first time it works and serves user-uploaded files, but if I refresh the page, then it doesn't work! what's the problem??
Upvotes: 1
Views: 986
Reputation: 946
Thats because the static and media files are not served by django in production. Thats why it works when you make DEBUG = True,
What you need to do is to setup an alias for media files in your nginx config for your site, inside your server block just like static files, like this:
location /files/ {
autoindex on;
alias /home/your/project/uploaded_files/;
}
Also, dont forget to restart your nginx afterwards.
Upvotes: 1
Reputation: 3483
you must define in urls.py
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', Index.as_view(), name='index'),
]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Upvotes: 0