I've already tried the solution here and it didn't work for me. I'm creating a project based off the Heroku "Getting Started" project for Python.
In views.py, I'd like to be able to access a file in the static/data/ folder. However, most of my attempts I make to create the correct url to the file have failed. The only thing that works is putting the absolute path to the file as it exists on my local file system, which obviously won't work when I deploy my app.
Previous attempts to open the file include:
from django.templatetags.static import static
url = static('data/foobar.csv')
os.path.isfile(url) # False
from django.conf import settings
url = os.path.join(settings.STATIC_URL, 'data/foobar.csv')
os.path.isfile(url) # False
Here is my directory structure:
/appname
/app
/templates
views.py
/appname
/static
/js
/css
/data
settings.py
urls.py
settings.py:
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app'
)
MIDDLEWARE_CLASSES = (
'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 = 'appname.urls'
WSGI_APPLICATION = 'appname.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
DATABASES['default'] = dj_database_url.config()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
ALLOWED_HOSTS = ['*']
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
Instead of joining the STATIC_ROOT with the filename, use the staticfiles_storage interface instead. This will also work with remote static files like S3/django-storages.
from django.contrib.staticfiles.storage import staticfiles_storage
url = staticfiles_storage.url('data/foobar.csv')
With staticfiles_storage you can also do simple file operations like open, delete, save.
The particular staticfiles storage backend you've configured will provide both a path method and a url method.
from django.contrib.staticfiles.storage import staticfiles_storage
p = staticfiles_storage.path('data/foobar.csv')
content = p.readlines()
# manipulate content
The .url method returns the same value as Django's static built-in
url = static('data/foobar.csv')
When you deploy a Django application to Heroku, or when you manually run manage.py collectstatic task, all the static assets will be copied to your STATIC_ROOT directory. Therefore you should use:
file_path = os.path.join(settings.STATIC_ROOT, 'data/foobar.csv')
STATIC_ROOT = 'staticfiles' is your problem. From the docs, STATIC_ROOT is:
The absolute path to the directory where collectstatic will collect static files for deployment.
Currently, you don't even have a path listed there...
Your static files are not at the same place when you are in "dev" or "prod".
In dev, you use the django "runserver" command which will serve your static file with "original" files (eg : myproject/src/appname/static/appname/images/plop.jpeg)
In production mode, you must use the "collectstatic" django command which will copy those original file in a "direct public http access folder" (eg : /static/appname/images/plop.jpeg for an http access)
But original files are still at the same place (myproject/src/appname/static/appname/images/plop.jpeg), so your view can access those original file directly.
If you know in which app the file your are looking for is, it is very simple. If you want to use the "static overwrite" mecanims of Django, have a look to its functions to get the "final" static file (for exemple, is it myproject/python-env/lib/python2.7/site-packages/coolapp/static/coolapp/images/plop.jpeg or myproject/src/myapp/static/coolapp/images/plop.jpeg)
I recommend to read the Django Doc about static finders to better understand how it works : https://docs.djangoproject.com/en/3.1/ref/settings/#std:setting-STATICFILES_FINDERS
PS : "HTTP path" and "python path" are not the same ;)
Just had the same problem. Don't know if this is the best solution.
In settings.py I created two paths for switching between productive and development. I need to uncomment when deploying the site.
#Productive
#STATIC_ROOT = '/home/DimiDev/RESite/static'
#Development
STATIC_ROOT = 'realestate/static'
And in my python file, as already stated in this post.
from django.contrib.staticfiles.storage import staticfiles_storage
file_path = staticfiles_storage.path('realestate/ml/2xgBoosting_max.sav')
My structure for this file:
RESite\realestate\static\realestate\ml\2xgBoosting_max.sav
Let me tell you what I did, I made an app in which I had to read a CSV file.
I made the main project directory with django-startproject command and then made an app.
In the root I made a folder named static and inside that, I placed the CSV file.
Now in my views.py
read_csv('static/file_name')
All other settings were default and this worked for me!
What you are trying to do can be achieved the following way.
First as your settings.py file has this base path:
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
You can get files in your static directory this way:
url = os.path.join(settings.BASE_DIR, 'static/data/foobar.csv')
os.path.isfile(url) # True
Related
As I state in the title, when I set DEBUG = False in my project's settings file, the files from my media directory (the one the user uploads) don't display. The files from my static directory (the CSS and JavaScript files) load properly.
I looked at this answer, but I don't understand the prerequisites to get this to work. I am testing this on my local machine, where I only have Django and PostgreSQL installed. I don't have any Apache servers running, as far as I'm aware. I want to deploy my app on Amazon AWS, so I'd like to try out how it will look in production there before I deploy it to Amazon AWS.
Here are the relevant parts of my settings.py file:
DEBUG = False
ALLOWED_HOSTS = ['*']
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'
STATICFILES_DIRS = [
BASE_DIR / "static",
'/var/www/static/',
]
Willem Van Onsem is right on the media files. Since the static file is OK, for the workaround, you can add this line to your urls.py in the folder containing settings.py:
from django.conf.urls.static import static
from django.conf import settings
urlpatterns+=static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I'm new to Django. First I'll explain my issue and my logic. I want to make my filepaths RELATIVE as opposed to the ABSOLUTE they are now so I can work on my laptop and PC and have everything show up as is.
I know I'll have to alter MEDIA_URL in the settings.py below. Does
MEDIA_URL = os.path.join(BASE_DIR, 'articles/static/articles/media/')
STATIC_URL = os.path.join(BASE_DIR, 'articles/static/')
make sense? I mean logically to me its saying from BASE_DIR which prints to C:\Users\kevIN3D\Documents\GitHub\articleTestProject\articleTestSite, would step into articles/static/articles/media/ or does the fact that
BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))
is abspath(...) change everything?
settings.py
"""
Django settings for articleTestSite project.
Generated by 'django-admin startproject' using Django 1.8.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir))
MEDIA_ROOT = 'C:/Users/kevIN3D/Documents/GitHub/articleTestProject/articleTestSite/articles/static/articles/'
MEDIA_URL = '/media/'
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '2u#9=qkari39(465g+u!2t7*9tt_pdv)%155jdgxnki5#jujje'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'articles',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'articleTestSite.urls'
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',
],
},
},
]
WSGI_APPLICATION = 'articleTestSite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC-5'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_ROOT = 'C:/Users/kevIN3D/Documents/GitHub/articleTestProject/articleTestSite/articles/'
STATIC_URL = '/static/'
urls.py
urlpatterns = [
url(r'^articles/', include('articles.urls')),
url(r'^$', HomePage.as_view(), name='home'),
url(r'^admin/', include(admin.site.urls)),
] + static(settings.MEDIA_ROOT)
My issue is when I try to use '/' in my declaration it prints out the filename as 'C:\Users\kevIN3D\Documents\GitHub\articleTestProject\articleTestSite\articles/static/' so it uses incorrect slashes for myself.
How do I go about making my page have relative filenames? I want to be able to work on this between my laptop and my PC, but as it currently stands I can only work on it on my PC because all the filenames are absolute and just give me broken links on my laptop.
Here is a link to the repository Github Repository. Please any help would be appreciated, I'm completely stumped. If someone could get that working, with images and custom CSS and then kind of walk me through what you did. Its my first time trying to distribute a Django file to more then just the local host.
Let me explain settings:
Right wave to separate the path
Pass every folder to the os.path.join() method. Example:
os.path.join(BASE_DIR, 'articles', 'static')
STATIC_URL, MEDIA_URL
This variables are passed to your template context proccessor (if you use django.template.context_processors.media) without any changes. This variables are used to make client-side links to your static and media content.
You should set your STATIC_URL and MEDIA_URL manually. Like that:
STATIC_URL = "/static/"
MEDIA_URL = "/media/"
Then you can use them in templates:
<img src="{{STATIC_URL}}img/logo.png">(...)
STATIC_ROOT, MEDIA_ROOT, STATICFILES_DIRS
STATIC_ROOT is used to bring all your static files in one place by collectstatic command (if you're using django simple server, you shouldn't care about it).
STATICFILES_DIRS is the folder when your django simple server (manage.py runserver command) gets files to serve. If you will run collectstatic command, evety file from every dir listed in STATICFILES_DIRS copied be moved in STATIC_ROOT.
MEDIA_ROOT is the folder where Django will hold user-uploaded files (ImageField, FileField)
You should use absolute path in STATIC_ROOT, MEDIA_ROOT, STATICFILES_DIRS:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
STATIC_ROOT = os.path.join(BASE_DIR, 'media')
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'example', 'static', 'folder',)
Please note. If you have static folder in your app folder and your app is listed in INSTALLED_APPS this folder will be added to your STATICFILES_DIRS automatically.
Serving static and media files during development
It's really simple just add this lines after your urlpatterns:
urlpatterns = patterns('',
... your patterns...
) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
And don't forget to include settings:
from django.conf import settings
Serving on production server
Run collectstatic command to bring all your static content in one place.
Server your static and media folder using your apache/nginx/etc server:
Alias /media/ /path/to/your/media
Alias /static/ /path/to/your/static/
So I think I figured it out,
I was looking at things far to high-level so to speak. When in reality the answer was just simple. After giving myself a
print(BASE_DIR)
and having it spit out C:\Users\kevIN3D\Documents\GitHub\articlesTestProject\articleTestSite I realized all I needed to do was append that to my different ROOT variables.
MEDIA_ROOT = 'C:/Users/kevIN3D/Documents/GitHub/articleTestProject/articleTestSite/articles/static/articles/'
was my old MEDIA_ROOT, this was clearly absolute. BUT from this I can see that it shares that same filepath as BASE_DIR, so I went from there and
MEDIA_ROOT = 'C:/Users/kevIN3D/Documents/GitHub/articleTestProject/articleTestSite/articles/static/articles/'
became
MEDIA_ROOT = os.path.join(BASE_DIR, 'articles/static/articles/').replace('\\', '/') #run replace to convert UNIX slashes on Windows slashes
I had to do the same thing for STATIC_ROOT
STATIC_ROOT = 'C:/Users/kevIN3D/Documents/GitHub/articleTestProject/articleTestSite/articles/'
became
STATIC_ROOT = os.path.join(BASE_DIR, 'articles')
I know there are lots of these questions already but I haven't been able to find an answer. I'm trying to get my homepage to load but I have been getting this error:
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 1.7.1
Exception Type: TemplateDoesNotExist
Exception Value:
base.html
Exception Location: /Users/user/.virtualenvs/screen_savers/lib/python3.4/site-packages/django/template/loader.py in find_template, line 136
Python Executable: /Users/user/.virtualenvs/screen_savers/bin/python
Python Version: 3.4.1
Python Path:
['/Users/user/Devspace/scren_savers/the_screen_savers',
'/Users/user/.virtualenvs/screen_savers/lib/python34.zip',
'/Users/user/.virtualenvs/screen_savers/lib/python3.4',
'/Users/user/.virtualenvs/screen_savers/lib/python3.4/plat-darwin',
'/Users/user/.virtualenvs/screen_savers/lib/python3.4/lib-dynload',
'/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4',
'/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/plat-darwin',
'/Users/user/.virtualenvs/screen_savers/lib/python3.4/site-packages']
and can't seem to figure out why. I specified my TEMPLATE_DIR properly in my settings.py and made sure that the file exists where is says it does. I have also looked through all of these questions where people had the same problem but none of them solved my problem:
Django App template Loader, can't find app templates
Django template Path
Django can't find template
Django TemplateDoesNotExist?
Template does not exist
Django cant find templates
What really confuses me is that if I check the value of BASE_DIR and TEMPLATE_DIR it gives me:
/Users/user/Devspace/scren_savers/the_screen_savers
/Users/user/Devspace/scren_savers/the_screen_savers/templates
respectively which is exactly what I expect to see. It seems like it knows where the templates are but still can't see them. Any help would be greatly appreciated.
Also an additional, less important question:
I have seen BASE_DIR + '/templates' and os.path.join(BASE_DIR, "templates") suggested as the proper way to specify the TEMPLATE_DIR. Is one of these better than the other (if so why) or is this just a matter of personal preference?
Here is the view that I am trying to load:
from django.http import HttpResponse
from django.shortcuts import render
from django.views.generic import View
class home_page(View):
def get(self, request):
return render(request, 'base.html')
and here is my settings file:
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
TEMPLATE_DIR = (
BASE_DIR + "/templates/",
)
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'screen_savers',
)
MIDDLEWARE_CLASSES = (
'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 = 'screen_savers.urls'
WSGI_APPLICATION = 'screen_savers.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.6/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.6/howto/static-files/
STATIC_URL = '/static/'
You should change in file settings.py TEMPLATE_DIR to TEMPLATE_DIRS.
I have recently started a Digital Ocean server with a pre-installed Django image on Ubuntu 14.04. I wanted to create an API, and have decided on the Django Rest Framework. I installed the Django Rest Framework exactly according to http://www.django-rest-framework.org/.
Here is what the tutorial site looks like when I access it on my server.
As you can see, it does not look like the site on the rest framework tutorial website. This is because of the fact that when I view the source code of my site, all of the /static/rest_framework/* files give me a 404 error.
Here is my settings.py file in the Django 'django_project' root directory.
"""
Django settings for django_project project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '7Vnib8zBUEV3LfacGKi2rT185N36A8svyq8azJLvNpv7BxxzMK'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
)
REST_FRAMEWORK = {
# Use hyperlinked styles by default.
# Only used if the `serializer_class` attribute is not set on a view.
'DEFAULT_MODEL_SERIALIZER_CLASS':
'rest_framework.serializers.HyperlinkedModelSerializer',
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}
MIDDLEWARE_CLASSES = (
'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 = 'django_project.urls'
WSGI_APPLICATION = 'django_project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'django',
'USER': 'django',
'PASSWORD': 'yj4SM6qcP0',
'HOST': 'localhost',
'PORT': '',
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.6/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.6/howto/static-files/
STATIC_URL = '/static/'
Can anyone help me fix this missing /static/rest_framework/ location error? If I am going to have an API for my application I would like it to be a good looking one.
Let me know if you need anything else to help you fix this, and thank you in advance for your help.
I have found the solution to my problem!
After much mind boggling research, I re-read this stack overflow question that didn't seem to help me the last time I took a look at it.
My new settings.py in my django_project folder now looks like this.
"""
Django settings for django_project project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'DwGCDqtcqzzGO2XK87u7bVSEUqHogZRFl4UdhkcCudSHxLUVvx'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
)
REST_FRAMEWORK = {
# Use hyperlinked styles by default.
# Only used if the `serializer_class` attribute is not set on a view.
'DEFAULT_MODEL_SERIALIZER_CLASS':
'rest_framework.serializers.HyperlinkedModelSerializer',
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}
MIDDLEWARE_CLASSES = (
'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 = 'django_project.urls'
WSGI_APPLICATION = 'django_project.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'django',
'USER': 'django',
'PASSWORD': 'mpOQzpYFci',
'HOST': 'localhost',
'PORT': '',
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.6/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.6/howto/static-files/
STATIC_ROOT = '/home/django/django_project/django_project/static'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
I now have a folder named 'static' right next to my settings.py file in my django_project folder with all necessary resources such as 'rest_framework' and 'admin'. I restarted gunicorn after this change and reloaded my web page and it worked!
Thanks to those of you who tried to help, you did lead me in the right direction and probably made this go by a lot faster.
First, You need to set static url and static root in django settings.py
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static")
Then collect all static files
python manage.py collectstatic
In my case I was relying on Gunicorn to run the server.
I tried updating my settings.py file by following the above threads but unfortunately nothing seemed to work for me.
In the end I scratched my head around DRF docs specially this part https://docs.djangoproject.com/en/dev/howto/static-files/
I managed to solve this problem by updating by urls.py as following.
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('admin/', admin.site.urls),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Then updating my settings.py as follows.
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
And now execute => python manage.py collectstatic
I did this tens of times and I was going insane over it. I had DEBUG = False.
If you're using Heroku to serve your website, try this link. It worked for me.
https://devcenter.heroku.com/articles/django-assets
In Summary:
Make a static folder if you don't have one already. (put it on the same level as your manage.py file)
Add the Python package to the folder (Copy this folder into the static folder --> C:\Python37_64\Lib\site-packages\rest_framework)
Add the code below to your project.
settings.py
...
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
...
MIDDLEWARE_CLASSES = (
# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
'whitenoise.middleware.WhiteNoiseMiddleware',
...
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
# Extra places for collectstatic to find static files.
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
requirements.txt
...
#add whotrnoise to requirements
whitenoise
I had the same issue when I started learning python. I fixed by making below changes in settings.py of my project
DEBUG = True
I was unable to get any of the above solutions to work on our webapp, but discovered that if the app can connect to an S3 bucket where it can access deployed static files, django rest_framework works pretty seemlessly (as discussed here). Here's the relevant code for our settings.py:
aws = pcfenv.get_service(label='aws-s3') # or however you are accessing your s3 bucket & credentials
if aws is not None:
keys = aws.credentials
AWS_ACCESS_KEY_ID = keys["access_key_id"]
AWS_SECRET_ACCESS_KEY = keys["secret_access_key"]
AWS_STORAGE_BUCKET_NAME = keys["bucket"]
AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
AWS_S3_OBJECT_PARAMETERS = {
'CacheControl': 'max-age=86400',
}
AWS_LOCATION = 'static'
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
STATIC_URL = "https://%s/%s/" % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION)
DEFAULT_FILE_STORAGE = 'mysite.storage_backends.MediaStorage'
# static files
STATIC_URL = '/static/'
STATIC_ROOT = 'static/'
# local storage
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/uploads/'
You'll need to pip install the boto3 and django-storages dependencies for it all to work.
you need both:
REST_FRAMEWORK = {
# Use hyperlinked styles by default.
# Only used if the `serializer_class` attribute is not set on a view.
'DEFAULT_MODEL_SERIALIZER_CLASS':
'rest_framework.serializers.HyperlinkedModelSerializer',
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}
and
the
python manage.py collectstatic
with the relevant directories set up.
the latter without the former won't do the work.
In debug mode, no changes are required.
If you are in a production environment, you need to set the static files point, usually set in nginx
location /static {
alias /<your app>/static; # your Django project's static files - amend as required
}
I have been trying out the Django tutorialDjango Tutorial Page 3 and encountered this error
"TemplateDoesNotExist at /polls/ " .
I assume the problem is with my code pointing the templates file index.html. This is my file structure for index.html: mysite/polls/templates/polls.
I am copying my settings.py and views.py here.
settings.py
TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]
views. Py
from django.shortcuts import render
from django.http import HttpResponse
from django.template import RequestContext, loader
from polls.models import Poll
# Create your views here.
#def index(request):
#return HttpResponse("Hello, world. You are at the poll index.")
def index(request):
latest_poll_list = Poll.objects.order_by('-pub_date')[:5]
template = loader.get_template('polls/index.html')
context = RequestContext(request, {
'latest_poll_list': latest_poll_list,
})
return HttpResponse(template.render(context))
def detail(request,poll_id):
return HttpResponse("You're looking at the results of the poll %s." % poll_id)
def results(request, poll_id):
return HttpResponse("You're looking at the results of poll %s." % poll_id)
def vote(request,poll_id):
return HttpResponse("You're voting on poll %s." % poll_id)
Can someone look into it and help me to solve this error. Any help would be appreciated.
This is the traceback `Environment:
Request Method: GET
Request URL: http://localhost:8000/polls/
Django Version: 1.6.4
Python Version: 3.4.0
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls')
Installed Middleware:
('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')
Template Loader Error:
Django tried loading these templates, in this order:
Using loader django.template.loaders.filesystem.Loader:
C:\Python34\mysite\templates\polls\index.html (File does not exist)
Using loader django.template.loaders.app_directories.Loader:
C:\Python34\lib\site-packages\django\contrib\admin\templates\polls\index.html (File does not exist)
C:\Python34\lib\site-packages\django\contrib\auth\templates\polls\index.html (File does not exist)
C:\Python34\mysite\polls\templates\polls\index.html (File does not exist)
Traceback:
File "C:\Python34\lib\site-packages\django\core\handlers\base.py" in get_response
114. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python34\mysite\polls\views.py" in index
14. template = loader.get_template('polls/index.html')
File "C:\Python34\lib\site-packages\django\template\loader.py" in get_template
138. template, origin = find_template(template_name)
File "C:\Python34\lib\site-packages\django\template\loader.py" in find_template
131. raise TemplateDoesNotExist(name)
Exception Type: TemplateDoesNotExist at /polls/
Exception Value: polls/index.html`
Please let me know if i missed out anything that would give a more clear picture. Thanks in advance.
Settings.py """
Django settings for mysite project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'ma_x5+pnvp$o7#5g#lb)0g$sa5ln%k(z#wcahwib4dngbbe9^='
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls',
)
MIDDLEWARE_CLASSES = (
'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 = 'mysite.urls'
WSGI_APPLICATION = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'C://Python34/mysite/db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
#TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/
STATIC_URL = '/static/'
Whoa whoa whoa. Let's not advocate non re-usability of apps.
For templates that don't fit anywhere else (usually your base template, maybe some partial templates like form includes, etc.), it's fine to put them in your root templates directory (ie. /path/to/project/templates/base.html). You would refer to them in a view for rendering as base.html.
For other templates, I would advise you put them in the directory of the app that contains the views that render to those templates. For example, your polls index would go somewhere such as /path/to/project/polls/templates/polls/index.html.
The extra polls directory may look redundant there, but the reason is that the django template loader will (logically) dump all your templates in one directory. So we use the second polls directory to differentiate between multiple index.html templates that may exist. So in your view, you would use polls/index.html as normal.
The reason that this is a Good Thing is that it makes your apps more easily reusable. Written one polls app? You've written them all. If you do this, and also keep your app specific static files (js, css, images, etc.) in your app's static directory, and have a urls.py for each app, generally all you will need to do to move your app from one project to another is copy the directory, add to the new project's INSTALLED_APPS, and include the urls from your base urls.py. And of course, modify the app in any way you need to for the new project.
It also means if you're using an editor with sidebar navigation (most of them, these days), you don't have to scroll all the way down to your templates to find the template for that app. When you start working on large projects this gets tedious, fast.
The only thing to remember in using this technique is that you must have django.template.loaders.app_directories.Loader in your TEMPLATE_LOADERS setting. This is the default so you usually won't have to worry about it.
There is a nice guide for this in the django docs: https://docs.djangoproject.com/en/1.7/intro/reusable-apps/
To answer the question you actually asked:
Your index.html should be here: C:\Python34\mysite\polls\templates\polls\index.html. If it isn't, that's what you're doing wrong.
On a related note, you probably shouldn't have your project in the Python directory.
Try to put template folder in projects root folder:
mysite/templates/polls/index.html
Explanation
Your template dirs is
TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]
It containts only one directory: /path/to/your/project/templates
And your index.html located in /path/to/your/project/polls/templates
Update
As you say it doesn't work with templates stored in mysite/templates/polls/index.html let's try this way:
go to mysite and run
python manage.py shell
to run interactive interpreter with mysite as context. Then run this:
from settings import TEMPLATE_DIRS
print TEMPLATE_DIRS
it will output something like
('/var/www/mithril/templates/', '/home/dmitry/proj/mithril/templates/')
Django uses this directories to find your templates.
Thus you should put directory polls/ in folder from TEMPLATE_DIRS.
You forgot to add your app config in the INSTALLED_APP in settings.py
INSTALLED_APPS = (
'polls.apps.PollsConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
)
The startapp command creates an apps.py file. Since it doesn’t use default_app_config (a
discouraged API), you must specify the app config’s path, e.g. 'polls.apps.PollsConfig', in
INSTALLED_APPS for it to be used (instead of just 'polls').
I was having the same problem and I noticed there was another HTML file named index in site-packages. So I just changed my current HTML file to index1 and it worked.
Try to replace:
template = loader.get_template('polls/index.html')
with this:
template = loader.get_template('index.html')
Check if you forgot the 's' in
/polls/template
its
'/polls/templates' folder.
In your settings.py file, add this
TEMPLATE_DIR = os.path.join(BASE_DIR,'templates')
And then in TEMPLATES DIRS, add this,
TEMPLATES = [
{
...
'DIRS': [TEMPLATE_DIR,],
...
},]
The issue is with your folder structure. Since you are inside the polls folder, you should have this template = loader.get_template('index.html') instead of template = loader.get_template('polls/index.html')
This is because of how the python path works, see here OS Path
You follow this structure,
mysite/
mysite/
templates/
polls/
index.html
there's something suspect to your TEMPLATE_DIRS path. It should point to the root of your template directory.
import os
PROJECT_PATH = os.path.realpath(os.path.dirname(__file__))
...
TEMPLATE_DIRS = (
os.path.join(BASE_DIR, 'templates'),
)
In your error log django searching these paths,
C:\Python34\mysite\templates\polls\index.html
C:\Python34\mysite\polls\templates\polls\index.html
Make sure you didn't misspell detail.html as details.html. This was my problem.
you should have placed your templates inside poll app inside templates/polls/ structured. Such that the full path will look like mysite/polls/templates/polls/file.html
I had the same issue running through the tutorial. None of the above answers worked for me.
my solution:
make sure when you are saving your html files, click SAVE AS and then click the file type and click "All Files". My index.html file was actually index.html.txt and was not being found.