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!
I have just deployed (first time ever) a Django project to a web server. Everything (including postgres) works flawlessly, except that static images won't load.
Here is the relevant part of the settings.py:
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static/")
#STATICFILES_DIRS = [
# os.path.join(BASE_DIR, "static"),
#]
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
LOGIN_REDIRECT_URL = 'home'
LOGIN_URL = 'login'
LOGOUT_URL = 'logout'
AUTH_USER_MODEL = 'account.CustomUser'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
The error message I get is the following in the console:
"GET /static/images/logo.png HTTP/1.1" 404 1808
However, when checking the file path in the console I have the following:
root#melius:/django/melius/static/images#
In this folder the files are present.
Where is my mistake?
There can be two reaon your static files not working.
First of all, Django doesn't serve static files on production.
Also i notice your static settings are wrongly configured.
Make sure your setting.py is look like this:
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'YOUR STATIC FILE FOLDERS')]
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
If you run your application on Nginx or apache2please make sure you configured the.conf` file properly to serve the static files.
Also, there is a straightforward and easy solution, that is whitenoise
If you don't want to serve your static files with Nginx or a similar server.
You can try whitenoise
To use whitenoise, please install it first and update your settings.py file like this:
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
and add this in middlware before the sessionmiddleware
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware', # Serve static in production without nginx or apache
'django.contrib.sessions.middleware.SessionMiddleware',
........
]
Hope the solution will solve your problem
Here you go for whitenoise docs: http://whitenoise.evans.io/en/stable/
Note: static root and static dirs shound't be same
I use django and my site works perfect but cant load images. I guess wrong thing is paths but i can't fix it. I see questions like that and apply all of them to my site but they did not work, please someone help me, i can't solve that for a few days.
NOTE : my site works fine on localhost, on my computer but don't work on server
Create a folder called static in your project directory or your app directory. Create another folder inside static called images.
In your settings.py file, add this line.
STATIC_URL = '/static/'
In your template file add this to the first line.
{% load static %}
In your template, use code like this to get the image to show.
<img src="{% static "image/example.jpg" %}"/>
Add the following lines in settings.py.
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
Finally go to your server project folder and use the following command.
python manage.py collectstatic
This command will copy all static files (e.g. images) from you static folders and paste it in folder you mentioned in STATIC_ROOT, in this case the folder is staticfiles.
Hope this helps.
Not sure if this is still of interest, but have been having the same problem and I had to do some searching. Here is the solution (https://docs.djangoproject.com/en/3.2/howto/static-files/deployment/ )
My understanding is that STATIC_ROOT acts as a "management repository" after you run collectstatic, and Django doesn't serve the files from there. You need to set up a separate folder. This is because in production, as flagged above, the suggestion is to have a separate server dedicated to such files.
In my case, I just created a separate folder next to static,
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'staticfiles'),)
Note, that this is NOT THE RECOMMENDED PLACE to PUT IT, and the above STATICFILES_DIRS should be separate, OUTSIDE your project folder/on a separate server. I put it there as my project was small, for testing purposes.
As flagged in the official documents too, you need to run collectstatic everytime a file there changes, and AFTER THAT you need to COPY THE FILES to the directory from where they are actually served, ie the directory that DJANGO is actually reading.
No changes are needed to the template(s).
Small add-on: the above is necessary (at least I found it so) for media/image files. Does not apply to the css/js files, which work just fine out of the normal '/static/' folder. Wanted to add this as I found LOTS of guides/explanations about setting up this '/static/' folder and collect static, but almost none about taking the additional step of moving images to a separate folder, STATICFILES_DIRS (or whatever name you want to set).
it is not about path, i guess. Becuse here is another basic project
enter image description here
views
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return HttpResponse("<h1><img src='static/ben2.jpg'></h1>")
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: keep the secret key used in production secret!
SECRET_KEY = 'key
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['my_server_ip']
# Application definition
INSTALLED_APPS = [
'webapp',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'web.urls'
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',
],
},
},
]
WSGI_APPLICATION = 'web.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-
validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME':
'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'
,
},
{
'NAME':
'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME':
'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME':
'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
I have tried all combinations like what you said :D but they did not help me
Below STATIC_URL line, insert this :
STATIC_ROOT = os.join.path(BASE_DIR, 'static')
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 am new to Django. I made a folder named templates in my project and "base.html" inside it, it works fine. But when I make new folder inside templates welcome and then "home.html" and I write some lines of code in my views.py file as
from django.shortcuts import render_to_response
def hello(request):
return render_to_response('welcome/home.html')
and settings.py includes
# Django settings for Telecom project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
import os
#BASE_DIR = os.path.dirname(os.path.dirname(__file__))
PROJECT_DIR = os.path.dirname(__file__)
ADMINS = (
# ('Your Name', 'your_email#example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'mysql', # Or path to database file if using sqlite3.
'USER': 'root', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '127.0.0.1', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '3306', # Set to empty string for default. Not used with sqlite3.
}
}
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/{{ docs_version }}/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# On Unix systems, a value of None will cause Django to use the same
# timezone as the operating system.
# If running in a Windows environment this must be set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'UTC'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale
USE_L10N = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media')
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = 'http://localhost:8000/media/admin/'
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# URL prefix for admin static files -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
# Examples: "http://foo.com/static/admin/", "/static/admin/".
ADMIN_MEDIA_PREFIX = '/static/admin/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'b9_hyqe*b&ra_&wlm5a9xas_ag#5mjv-dy=to%hdk_u-#xvn*l'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
TEMPLATE_DIRS = (
os.path.join(PROJECT_DIR, 'templates'),
)
print PROJECT_DIR
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
ROOT_URLCONF = 'Telecom.urls'
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
'django.contrib.admindocs',
'welcome',
)
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
but the error shows
TemplateDoesNotExist at /hello/
/welcome/home.html
Request Method: GET
Request URL: http://localhost:8000/hello/
Django Version: 1.6
Exception Type: TemplateDoesNotExist
Exception Value:
/welcome/home.html
Exception Location: C:\Python27\django\template\loader.py in find_template, line 131
Python Executable: C:\Python27\python.exe
Python Version: 2.7.2
Python Path:
['D:\\Bishnu\\BE\\4th year\\8th semester\\Major Project II\\Working\\Workspace\\Telecom',
'C:\\Python27\\lib\\site-packages\\distribute-0.6.35-py2.7.egg',
'D:\\Bishnu\\BE\\4th year\\8th semester\\Major Project II\\Working\\Workspace\\Telecom',
'C:\\Python27\\DLLs',
'C:\\Python27\\lib',
'C:\\Python27\\lib\\plat-win',
'C:\\Python27\\lib\\lib-tk',
'C:\\Python27',
'C:\\Python27\\lib\\site-packages',
'C:\\Python27\\lib\\site-packages\\wx-2.8-msw-unicode',
'C:\\Windows\\SYSTEM32\\python27.zip']
Server time: Tue, 18 Jun 2013 17:09:07 +0545
How can I solve it ?
For Django 1.8 or above
you need to open the settings.py file and add the template path in the DIRS key of TEMPLATES list as a list of string.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['Secondjango/Secondjango/templates/welcome'], # <<<<<<<<Here
'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',
],
},
},
]
Thanks.
This error may arises due to the incorrect template directories
Try some change on settings.py as below
import os.path
Temp_Path = os.path.realpath('.')
...
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = '/static/'
...
TEMPLATE_DIRS = (
Temp_Path +"/template"
)
Then put all your template inside template folder and css/javascript file in static folder which is located inside your application folder. Hope this will solve your problem.
My suggestion don't put template folder inside application folder
Django will choose the first template it finds whose name matches, and
if you had a template with the same name in a different application,
Django would be unable to distinguish between them. We need to be able
to point Django at the right one, and the easiest way to ensure this
is by namespacing them. That is, by putting those templates inside
another directory named for the application itself.
Try this:
In your settings.py file replace
TEMPLATE_DIRS = (
os.path.join(PROJECT_DIR, 'templates'),
)
with
TEMPLATE_DIRS = (
os.path.join(PROJECT_DIR, 'templates'),
os.path.join(PROJECT_DIR, 'templates/welcome')
)
Then, in your code, just call render_to_response("home.html")
That should resolve your issue.
For Django 1.8 or above just Add the following in TEMPLATES DIR variable list in settings file
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['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',
],
},
},
]
This property points to template directory 'DIRS': ['templates'],
For Django 2.0, I edited the value DIRS of TEMPLATES in setting file to the entry directory of the project:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['.'], # here set DIRS to project's entry directory
'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',
],
},
},
]
and the problem solved on both Mac and Windows systems.
You can use:
in settigns.py
TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), '..', 'templates').replace('\\','/'),)
STATICFILES_DIRS = (
'static',
)
Please check if you have added your new application in the settings.py file under INSTALLED_APPS
Django compiles all the 'templates' folder from all the applications inside your project into a single 'templates' folder.
Please remember to create separate directory inside your applications 'template' folder to make it easier for the Django framework to find the template you are looking for.
suppose that you hace a django project "my_project", and the application "app_1" and "app_2"
my_project
-- my_project
-- manage.py
welcome
-- __init__.py
templates
-- home.html
-- models.py
-- views.py
app_1
-- __init__.py
templates
welcome
-- home.html
-- models.py
-- views.py
app_2
templates
a_subfolder
-- home.html
-- __init__.py
-- models.py
-- views.py
now, if you have some settings like.
#...
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
#...
INSTALLED_APPS = (
'app_2',
'app_1',
'welcome',
#...
)
#...
django will do that:
When you call render_to_response('welcome/home.html') (I think that some params are missing), django will look at "home.html" file in some some "welcome" folder in ALL aplications (in this case "app_1" and "app_2") that have a "templates" folder. (that is a convention)
EDIT
I have added you "welcome" app.
You have to call the method without app name render_to_response('home.html')
Check if there is any include tag in "hello.html" which has been given filepath that does not exist. The error raised comes up the same :-
TemplateDoesNotExist at /hello/
/welcome/home.html
Add template directory to your TEMPLATES in your project settings.py by 'DIRS': [os.path.join(BASE_DIR, 'templates')],
So the final TEMPLATES should be something like the following
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, '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',
],
},
},
]
Do this
-> Make sure your templates folder should be in root folder not in app folder
-> then goto your setting.py file and look for TEMPLATES = [ 'DIRS': ]
-> in DIRS put the path of your template folder like this 'DIRS':[r'path']
it will work
Another reason could be if the name of the folder in your app is template and not templates. Note 's' in the end.
Your settings.py file must be :
'DIRS': ["templates"]
Your templates folder must be under your main project name :
Like that
All I had to do was Install 'rest_framework' as one of the apps.
Have you created the file __init__.py inside your welcome folder?