I have a django (v1.1.1) on a server running Python 2.4. On my localhost/development computer the site works perfect. When I uploaded the files to the production server, it seemed to work fine, but after a page refresh I am receiving random TemplateDoesNotExist errors.
In the trace report I looked at the TEMPLATE_DIRS variable to make sure I was pointing to the right place, and it actually changes each time I refresh the page between this:
TEMPLATE_DIRS
('templates', '/var/www/vhosts/mysite.com/apps')
and this
TEMPLATE_DIRS
('templates', '/var/www/django-sites/apps/templates')
How is it possible that django/python is looking in two different locations when I refresh the page? After 3-4 attempts it suddenly works until I either refresh or go to the next page. The correct location is /var/www/vhosts/mysite.com/apps/templates which is definted in my settings.py file:
# Django settings for django-sites project.
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email#domain.com'),
)
MANAGERS = ADMINS
DATABASE_ENGINE = 'mysql'
DATABASE_NAME = 'mysite'
DATABASE_USER = 'mysuser'
DATABASE_PASSWORD = 'mypass'
DATABASE_HOST = 'www.mysite.com'
DATABASE_PORT = ''
# 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.
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 = 'en-us'
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = ''
# URL prefix for admin media -- CSS, JavaScript and images.
# Make sure to use a trailing slash.
ADMIN_MEDIA_PREFIX = '/admin_media/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'mysecretkey'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
# 'django.template.loaders.eggs.load_template_source',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
ROOT_URLCONF = 'apps.urls'
URL_ROOT_LEAD_CAPTURE = '/lead-capture/'
TEMPLATE_CONTEXT_PROCESSORS = (
'django.core.context_processors.request',
'django.core.context_processors.auth',
)
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
TEMPLATE_DIRS = (
os.path.join(PROJECT_ROOT, 'templates'),
'/var/www/vhosts/mysite.com/apps/templates',
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'django.contrib.admindocs',
)
I appreciate the help!
It sounds like a problem with your apache configuration or what ever you are using for the web server. The PROJECT_ROOT:
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
Is dependent upon the current absolute path which is set by what ever environment is running the application. Make sure that only one route for handling URLs exists in your web server configuration.
Second, make sure all django environments have been cleanly shutdown, you may have some old, misconfigured environments around serving requests.
Related
I am unable to save anything in my django non-rel development project..
I have google app engine sdk installed with django non -rel.
I can access the django admin page but cannot login because neither superuser is getting saved anywhere.
I tried creating user in manage.py shell.
But after closing the shell window, the user object i saved earlier was not there.
Please help me how to save data to database in django-non-rel..
My settings.py file is -
# Django settings for bookncart project.
# Initialize App Engine and import the default settings (DB backend, etc.).
# If you want to use a different backend you have to remove all occurences
# of "djangoappengine" from this file.
from djangoappengine.settings_base import *
ADMINS = (
# ('Your Name', 'your_email#example.com'),
)
MANAGERS = ADMINS
# Activate django-dbindexer for the default database
DATABASES['default'] = {'ENGINE': 'dbindexer', 'TARGET': DATABASES['default']}
AUTOLOAD_SITECONF = 'indexes'
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/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.
# In a Windows environment this must be set to 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 = 'en-us'
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
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = False
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL = ''
# 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: "/var/www/example.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = '/static/'
# 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 = 'l#ng7t0n-q4eb_*#3r04f1r09jf=&emqddc4a0!=yrvz(tbr23'
# 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',
)
MIDDLEWARE_CLASSES = (
# This loads the index definitions, so it has to come first
'autoload.middleware.AutoloadMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'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',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'bookncart.urls'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
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',
'django.contrib.staticfiles',
'djangotoolbox',
'autoload',
'dbindexer',
# djangoappengine should come last, so it can override a few manage.py commands
'djangoappengine',
)
# 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 when DEBUG=False.
# 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,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
and urls.py file is -
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'bookncart.views.home', name='home'),
# url(r'^bookncart/', include('bookncart.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)
the base settings for djangoappengine are these -
try:
from dev_appserver_version import DEV_APPSERVER_VERSION
except ImportError:
DEV_APPSERVER_VERSION = 2
# Initialize App Engine SDK if necessary.
try:
from google.appengine.api import apiproxy_stub_map
except ImportError:
from djangoappengine.boot import setup_env
setup_env(DEV_APPSERVER_VERSION)
from djangoappengine.utils import on_production_server, have_appserver
DEBUG = not on_production_server
TEMPLATE_DEBUG = DEBUG
ROOT_URLCONF = 'urls'
DATABASES = {
'default': {
'ENGINE': 'djangoappengine.db',
# Other settings which you might want to override in your
# settings.py.
# Activates high-replication support for remote_api.
# 'HIGH_REPLICATION': True,
# Switch to the App Engine for Business domain.
# 'DOMAIN': 'googleplex.com',
# Store db.Keys as values of ForeignKey or other related
# fields. Warning: dump your data before, and reload it after
# changing! Defaults to False if not set.
# 'STORE_RELATIONS_AS_DB_KEYS': True,
'DEV_APPSERVER_OPTIONS': {
'use_sqlite': True,
# Optional parameters for development environment.
# Emulate the high-replication datastore locally.
# TODO: Likely to break loaddata (some records missing).
# 'high_replication' : True,
# Setting to True will trigger exceptions if a needed index is missing
# Setting to False will auto-generated index.yaml file
# 'require_indexes': True,
},
},
}
if on_production_server:
EMAIL_BACKEND = 'djangoappengine.mail.AsyncEmailBackend'
else:
EMAIL_BACKEND = 'djangoappengine.mail.EmailBackend'
# Specify a queue name for the async. email backend.
EMAIL_QUEUE_NAME = 'default'
PREPARE_UPLOAD_BACKEND = 'djangoappengine.storage.prepare_upload'
SERVE_FILE_BACKEND = 'djangoappengine.storage.serve_file'
DEFAULT_FILE_STORAGE = 'djangoappengine.storage.BlobstoreStorage'
FILE_UPLOAD_MAX_MEMORY_SIZE = 1024 * 1024
FILE_UPLOAD_HANDLERS = (
'djangoappengine.storage.BlobstoreFileUploadHandler',
'django.core.files.uploadhandler.MemoryFileUploadHandler',
)
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'TIMEOUT': 0,
}
}
SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db'
if not on_production_server:
INTERNAL_IPS = ('127.0.0.1',)
please help me how to get database settings working..
i am unable to find a solution from 2 days
You can change your
ALLOWED_HOSTS = ['<Name of Application in YAML>.appspot.com']
For more details on ALLOWED_HOSTS
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
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'm learning django with this excellent book "Practical Django Projects". I was able to follow the steps of the book perfectly, but now I stumbled upon the following problem.
When creating the page http://127.0.0.1:8000/first-page/ as image below:
I found the following error page:
Slightly different of this one, announced on book (page 16):
Then, I openned the file urls.py and added to it the following line of code:
(r'', include ('django.contrib.flatpages.urls')),
And the code looks like this:
I saved urls.py and accessed http://127.0.0.1:8000/first-page/ again, finding the same error message above (nothing changed), when, according to the book, I should now have found this other error page:
As a result, after I create the directory and file default.html for templates, as follows:
And have changed the TEMPLATE_DIRS settings.py file like this:
Again, the http://127.0.0.1:8000/first-page/ shows that same error message when, this time should show this:
I have repeated several times the steps.
I'm using Python 2.6 and django 1.1 (the same version of the book).
Does anyone have any idea about what I'm doing wrong?
Thank you in advance for any help.
It all seems so simple and straightforward. And yet, does not work!
Here my settings file code:
# Django settings for cms project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email#domain.com'),
)
MANAGERS = ADMINS
DATABASE_ENGINE = 'sqlite3' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = 'C:\Projetos\cms\cms.db' # Or path to database file if using sqlite3.
DATABASE_USER = '' # Not used with sqlite3.
DATABASE_PASSWORD = '' # Not used with sqlite3.
DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3.
DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3.
TIME_ZONE = 'America/Chicago'
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
USE_I18N = True
MEDIA_ROOT = ''
MEDIA_URL = ''
ADMIN_MEDIA_PREFIX = '/media/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = ''
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
# 'django.template.loaders.eggs.load_template_source',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
ROOT_URLCONF = 'cms.urls'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
'C:/Projetos/templates/',
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'django.contrib.flatpages',
# Uncomment the next line to enable the admin:
# 'django.contrib.admin',
)
The answer to all errors was this (thanks, mongoose_za):
"On page 15 [of the book "Practical Django Projects"] you must make sure you edit the example.com site instead of adding a new site. You might have noticed in your settings.py the SITE_ID = 1. If you add a new site 127.0.0.1:8000 then that will have a SITE_ID of 2, and in the following section flatpage views filter by default on the current site which is 1."
So, I just change SITE_ID = 2 (instead of 1) in settings.py, because I had added a new site 127.0.0.1:8000.
After that, I changed the path to my templates folder according to instructions on the book to:
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
'C:/Projetos/templates/',
)
I found the expected result (the blank page "My first page")
I also have followed this advice:
"On p13 is where the first deviation from the older django kicks in. In your settings.py add 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware', (don't forget the comma) to your MIDDLEWARE_CLASSES."
All this was found on this great blog:
http://blog.haydon.id.au/2008/08/2-your-first-django-site-simple-cms.html
Firstly: the template does not exist error is because you dont have the template
C:/Projects/templates/flatpages/default.html (also in your screenshot your template dir is spelled "Projetos")
Secondly: you shouldnt need to add any the url rule for flatpages. Flatpages works via middleware:
'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
so within your settings file:
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
'django.middleware.common.CommonMiddleware',
#'debug_toolbar.middleware.DebugToolbarMiddleware',
)
The TemplateDoesNotExist error is not on your template, but on 500.html. There's an error in your code in your template or view and Django is responding with a 500 error. However, in development, you should have DEBUG = True, in which case Django will show a stacktrace instead of trying to load 500.html.
So the simple solution is to make DEBUG = True so you can see the real error and correct that. However, you'll still need 500.html when you finally launch, so you might as well go ahead and create that too.