i have problems with my django app. Since a few days i have the problem that the download dont work on production but i cant find the reason why...
I can upload files and they are stored in the correct folder, but as soon as i click on it i get a 404 error "file not found.."
Here is my setup:
settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
.
.
.
TEMPLATE_DIR = os.path.join(BASE_DIR, "templates")
STATIC_DIR = os.path.join(BASE_DIR, "static")
MEDIA_DIR = os.path.join(BASE_DIR, "media")
STATIC_ROOT = STATIC_DIR
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "staticfiles/static"),
]
MEDIA_URL = '/media/'
MEDIA_ROOT = MEDIA_DIR
MEDIA_TEMPLATE_ROOT = os.path.join(MEDIA_ROOT, 'templates')
MEDIA_TEMP = os.path.join(MEDIA_ROOT, 'tmp')
urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('jet/', include('jet.urls', 'jet')),
path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
I tried many different configurations of the media_url, media_root etc... without success..
In production, usually the django web app is behind a web server like nginx or apache http web server.
In that case, what is usually done is to configure your web server (nginx or apache) to serve directly the static files, thus you need to configure the virtualhost section.
If you can provide more information about your configuration, I could be more specific.
Thats the setup iam using:
https://lab.uberspace.de/guide_django/
Its my first time deploying the app on a server. Debug=False yes. The app it self works but it doesnt serve the files. But i have no clue what gunicorn does in this configuration, i just followed the link above to set it up.
The solution was to configure the uwsgi file:
static-map = /static=%(chdir)/staticfiles/static
There I modified the location of the media folder to the staticfiles/static folder. Then it worked!
Related
I removed the BASE_DIR and the os import because I am using django-environ.
However when I entered the admin dashboard of Django, the css is not read so I only see plain html elements.
Here is how part of my settings.py looks like.
import environ
root = environ.Path(__file__) - 3 # get root of the project
env = environ.Env()
environ.Env.read_env() # reading .env file
SITE_ROOT = root()
DEBUG = env.bool('DEBUG', default=False)
TEMPLATE_DEBUG = DEBUG
ALLOWED_HOSTS = tuple(env.str('ALLOWED_HOSTS', default=[]))
DATABASES = {
'default': env.db('DATABASE_URL')
}
SECRET_KEY = env.str('SECRET_KEY')
# Static and Media Config
public_root = root.path('public/')
MEDIA_ROOT = public_root('media')
# MEDIA_ROOT = root.path('media/')
MEDIA_URL = env.str('MEDIA_URL', default='media/')
STATIC_ROOT = public_root('static')
STATIC_URL = env.str('STATIC_URL', default='static/')
ROOT_URLCONF = 'myproject.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [root.path('templates/'), ],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
So I also put in root.path('templates') into the DIRS of TEMPLATES.
I also added this snippet below to the project's urls.py.
if settings.DEBUG:
urlpatterns += static(
settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT
)
I also have this on my .env file:
DEBUG=True
ALLOWED_HOSTS=localhost,127.0.0.1
MEDIA_URL=media/
STATIC_URL=static/
Where could I have gone wrong and what should be written instead?
I looked into djangogirls tutorial and found out that I missed out some slashes.
From my .env file:
MEDIA_URL=media/
STATIC_URL=static/
I changed it into
MEDIA_URL=/media/
STATIC_URL=/static/
static and media configuration in settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'frontend','build', 'static')
]
MEDIA_URL='/media/'
MEDIA_ROOT=os.path.join(BASE_DIR, 'media')
urls.py
from django.contrib import admin
from django.urls import path, include, re_path
from django.views.generic import TemplateView
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
re_path('', TemplateView.as_view(template_name='index.html')),
] + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
Here i am using django with reactjs.
i have given the path of build folder in react app like this.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'frontend','build')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
When i am going to http://127.0.0.1:8000/media/images_OkG6q2k.jpeg path to get images
in side media folder which are uploaded by users i am getting the react route page.
I am not getting the image from media folder.
How i can see the media photos through url.
Project structure
react home is coming instead media image like this when i amgoing url
I think I just overcame this problem with one of my projects with Django backend + React frontend. It is in your url patterns.
As I understand it, this catch-all pattern:
re_path('', TemplateView.as_view(template_name='index.html'))
essentially overrides the media url pattern you wrote (and any others below it), which prevents the Django backend from allowing you to access the media files. To fix this, simply make sure the catch-all route is the last one on your patterns. After you are done with the rest of the patterns, on a new line do this:
urlpatterns += [re_path('', TemplateView.as_view(template_name='index.html'))]
This way, you add it to your paths after all the rest and it doesn't "block" any of the others. hopefully this fixes it!
I'm new to Django and trying to figure out why the changes in static css and js files are not picked up by the browser.
Only after I run python manage.py collectstatic followed by restarting the server do I see the desired results.
Using Django 1.11 and python 2.7
Here is a glimpse of my settings.py
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = [u'customizeittoday.herokuapp.com', u'localhost']
# Application definition
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
#STATIC_URL = '/static/'
#static media settings
STATIC_URL = 'https://' + AWS_STORAGE_BUCKET_NAME + '.s3.amazonaws.com/'
MEDIA_URL = STATIC_URL + 'media/'
# STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), )
# STATIC_ROOT = 'staticfiles'
ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/'
STATICFILES_FINDERS = ('django.contrib.staticfiles.finders.FileSystemFinder','django.contrib.staticfiles.finders.AppDirectoriesFinder',)
This is old but I suspect this is because you are storing your static files on AWS S3. By default S3 uses a default cache-control header that specifies a 24 hour cache time.
You should probably migrate to using versioned static files.
You can use ManifestStaticFilesStorage which is designed to do this as part of the collectstatic cycle by appending hashes to filenames. By default it applies to all filetypes.
If you want to use it but want to specify which filetypes are versioned, then I wrote an extension that allows you to whitelist / blacklist files by path pattern.
Sometimes browser itself caches the CSS or js files and load them from the cache. To avoid that "disable cache" in the network tab of the developer console for the respective browser.
I'm using Vue + webpack with a Django backend for my webapp and I need to be able to serve files from the dist folder from Django when the user hits the root url '/'. The dist folder containing the static files from Vue + webpack has already been created, and I just need to know how to serve those files from Django. I disabled collectstatic on Heroku because all my files will be served from dist folder that was not generated by django.
I'm able to serve index.html from the dist folder but not the js and css files in there. The error i'm getting is /static/js/main.js not found
Here's what I have so far, but none of my attempts are working. I need some way to configure Django urlpatterns to serve the static files in the dist folder
settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, '../dist')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.static',
'django.contrib.messages.context_processors.messages',
],
},
},
]
STATIC_ROOT = os.path.join(BASE_DIR, '../dist')
STATIC_URL = '/dist/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, '../dist'),
]
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
urls.py
if settings.DEBUG is False:
urlpatterns += url(
urlpatterns += url(r'^$', generic.TemplateView.as_view(template_name='index.html')),
dist/
- index.html
- static
- js
- main.js
- css
- main.css
I would like to run Django from location https://www.example.com/someuri/ so that I have the admin interface at https://www.example.com/someuri/admin/. I can see the login window but when I log in I get redirected to https://www.example.com/admin/.
Where can I set the base URL of Django to https://www.example.com/someuri/? I tried with BASE_URL but with no luck.
#AgileDeveloper's answer is completely correct for that one off case of admin. However, is the desire to set it this way for all URLs? If so, perhaps you should do something like this
from django.conf.urls import include, url
from . import views
urlpatterns = [
url(r'^someuri/', include([
url(r'^admin/', include(admin.site.urls) ),
url(r'^other/$', views.other)
])),
]
I have a project that has a similar setup. I have django running using a virtual environment with apache. In my 000-default.conf file, I set the WSGIScriptAlias to the following:
WSGIScriptAlias /someuri /path/to/wsgi.py
Here is the documentation on WSGIScriptAlias to serve the project from a subdirectory, https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/modwsgi/#using-mod-wsgi-daemon-mode.
Than in the urls.py file I set the following:
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^', include('someuri.urls')),
url(r'^admin/', admin.site.urls),
]
After logging in, I am redirected to http://example.com/someuri/admin/
The answer of #James Wallace works well assuming you have control of the web server hosting Django at /someuri. In that configuration, the server will pass a value of SCRIPT_NAME in the header to Django, who will then know it is being served on that sub-path.
However, if you do not have control of the front-end server, then you can force Django to assume that value by adding to settings.py in the project:
USE_X_FORWARDED_HOST = True
FORCE_SCRIPT_NAME = '/someuri'
Afterwards, you may still have problems with static files, the css, etc., even in the admin application. In the default config, these are served by the Django development server without changes. However, with the above changes the static files will be lost. Assuming you still want to serve these files through the internal Django development server (and not through an external web server) you need to add to the settings.py project file:
STATIC_SUFFIX = '/static/'
STATIC_URL = FORCE_SCRIPT_NAME + STATIC_SUFFIX
MEDIA_SUFFIX = '/media/'
MEDIA_URL = FORCE_SCRIPT_NAME + MEDIA_SUFFIX
In the same file, you also need to change TEMPLATES and add the following:
STATIC_ROOT = os.path.join(BASE_DIR, "static/")
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [ STATIC_ROOT ],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
You will then want to gather the static files into the directory defined:
python manage.py collectstatic
or
python3 manage.py collectstatic
The project level urls.py file should look like this (Django v1.11):
import os
from django.conf.urls import url
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings
from django.views.generic.base import TemplateView
urlpatterns = [
url(r'^admin/', admin.site.urls),
] + static(settings.STATIC_SUFFIX, document_root=settings.STATIC_ROOT)
Thereafter, the admin package should work okay, with appropriate stylesheets and everything. The only thing that does not seem to work well is the "VIEW SITE" link since it misses a slash. I did not find a solution for that but probably it involves hacking the admin application.
Beyond that, there are various guides online for installing Django under a sub-path. It's messy but the above avoids the worst headaches.
This should work for you.
from django.conf.urls import patterns, url
urlpatterns = patterns('',
(r'^someuri/admin/', include(admin.site.urls) ),
)