Django can't find template - python

I know many people have asked, this question, but despite hardcoding the path to my template directory I can't seem to get Django to find my template.
Here is settings.py
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
#django.template.loaders.eggs.Loader',
)
TEMPLATE_DIRS = (
"/Users/full/path/to/marketing_site/templates",
)
This is the views.py file:
def static (request, feature_page):
# this will get the appropriate feature page template.
template = loader.get_template('features/pricing.html')
c = RequestContext(request,{
})
return HttpResponse(template.render(c))
Inside the main folder is the templates folder and the app folder. I use to put the apps in the same folder as settings.py but it appears django 1.4 has changed the default file structure.
My error is:
TemplateDoesNotExist at /features/pricing
Django tried loading these templates, in this order:
Using loader django.template.loaders.filesystem.Loader:
Using loader django.template.loaders.app_directories.Loader:
/Library/Python/2.7/site-packages/django/contrib/auth/templates/feature_pricing.html (File does not exist)
Update:
My logs for the webpage list the TEMPLATE_DIRS as ().
If I put a print statement on the settings.py page for the TEMPLATE_DIRS I get a printout of the TEMPLATE_DIRS appropriately... so somehow the TEMPLATE_DIRS isn't being used (from what it looks like)

I had added in an extra TEMPLATE_DIR in the settings.py
:(

it's better to set up relative paths for your path variables. You can set it up like so:
import os
PATH_PROJECT = os.path.realpath(os.path.dirname(__file__))
...
...
TEMPLATE_DIRS = (
PATH_PROJECT + '/templates/'
)
Also assuming you are using windows you may want to try:
TEMPLATE_DIRS = (
"C:/Users/full/path/to/marketing_site/templates",
)

I'm betting /Users/full/path/to/marketing_site/templates does not contain a features directory, or /Users/full/path/to/marketing_site/templates/features does not contain a pricing.html file.
Based on your comment, it looks like you're calling loader.get_template('feature_pricing.‌​html'), instead of using 'feature/pricing.html'.
EDIT: I didn't notice this before:
Inside the main folder is the templates folder and the app folder. I use to put the apps in the same folder as settings.py but it appears django 1.4 has changed the default file structure.
That could be causing the issue. Change the directory structure to match the 1.4 Django conventions. You might just recreate the project, copy the relevant settings over into the newly create settings.py, and copy all the files.

Try adding project paths to django.wsgi
import os
import sys
paths = ('path/to/project/',
'path/to/more /included/directories/',
)
for path in paths:
if path not in sys.path:
sys.path.append(path)
os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()

Related

Why can't Django detect a static file outside of my project folder in local?

In a Django template tag, I am returning a file path that is outside of my project folder. I am placing this in my template. My files look like this:
myproject (contains project, app, manage.py, etc)
myfolder
|
+----styles.css
In my template tag, this is what I am returning:
from myproject.settings import BASE_DIR
from pathlib import Path
...
def get_outside_file():
HOME_DIR = Path(BASE_DIR).parent
return os.path.join(HOME_DIR, 'myfolder/styles.css')
Unfortunately, in my template, I get this error:
"GET /Users/myusername/myfolder/styles.css HTTP/1.1" 404
I clearly have the file in that folder, but Django can't seem to detect it. How can I fix this issue? Thanks for any help.
BTW, I am on Mac OsX, if that helps.
Try adding your Path to STATICFILES_DIRSin settings.py like
HOME_DIR = Path(BASE_DIR).parent
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
os.path.join(HOME_DIR, 'myfolder/styles.css')]

Trouble setting-up directories to compile from in Django-Assets / Webassets

This is my current assets.py file:
from django_assets import Bundle, register
sass = Bundle(
'build/main.sass',
filters='sass',
output='css/main.css'
)
register('sass', sass)
Now I run into an issue with it saying Another bundle is already registered as "sass", but not seeing how to unregister it.
At any rate, I change register('sass', sass) to register('sass_all', sass) to get past the error. When I go to compile it is looking in my scripts directory where I keep manage.py. In settings.py I add:
ASSETS_ROOT = [
'static',
]
Which just has look in scripts/static which doesn't exist.
Tried:
# This is already in settings.py
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
# Added new line
ASSETS_ROOT = [
STATICFILES_DIRS,
]
It generates a couple errors: KeyError: 'directory', OSError: The environment has no "directory" configured, and AttributeError: 'list' object has no attribute 'startswith'. Really it is just one error that directory isn't defined, I think.
Read through environment documentation which is vague given my skill level. In assets.py adding Environment to import just says Could not import in Environment. Adding Environment.directory('static') results in Environment is not defined. Just directory('static') also results in directory is not defined. env = Environment() same thing. Tried adding directory='/static' to sass = Bundle(...) which just says TypeError: got unexpected keyword argument 'directory'.
Anyway, spent a few hours on it and stuck again. Documentation seems to indicate directory settings should go in assets.py and not settings.py, whereas ASSETS_ROOT should be going in settings.py.
Thanks again in advance!
~/portal-client
project_dir
apps
account
templates
account
login.html
forms.py
urls.py
views.py
home
templates
home
home.html
urls.py
views.py
results
assets.py
settings.py
urls.py
scripts
manage.py
static
build
main.js
main.sass
css
app.css
main.css
js
app.js
main.js
media
templates
base.html
footer.html
title.html
Continuation from this question: Trouble adding Django-Assets / Webassets directory to look for assets.py files
A quick point to note:
# This is already in settings.py
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
# After this line STATICFILES_DIRS is `[ 'BASE_DIR/static' ]`
# Added new line
ASSETS_ROOT = [
STATICFILES_DIRS,
]
# After this line, ASSETS_ROOT is `[ [ 'BASE_DIR/static' ] ]`
# i.e., an array of arrays
# I think you actually wanted:
ASSETS_ROOT = STATICFILES_DIRS[0]
# - or more explicitly -
ASSETS_ROOT = os.path.normpath(os.path.join(BASE_DIR, 'static'))
That said many of these issues look like they are being caused by a fairly non-standard django structure (i.e., that your manage.py is in the scripts directory rather than in BASE_DIR).

Get the path of "static" folder in django automatically

I am developing Django (1.6) app. In my app I have to use the static images to be displayed on the HTML pages (like magnifying glass for search box,logo,etc). After little bit of research I came to know that we have to create a folder (say "static") which holds the static images and then I have mention the path in my settings.py like shown below :
`STATIC_URL = '/static/'
STATICFILES_DIRS = (
"C:/Users/Welcome/Desktop/business/static/polls",
"C:/Users/Welcome/Desktop/business/static",
)`
I also added the code shown below in urls.py too after which I could get the images on my HTML pages.
urlpatterns = patterns(''......... ...........) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
My question now is every time I change the directory (current working directory or if I transfer the project to another pc ) I have to update the path in settings.py.
How to not do that ? how to get path of "static" folder automatically when I run my project. Please do help. What I'm missing ?
Normally the static files finder of django will expect that your app itself has a static sub-directory, and you can store everything there.
+ myproj
- manage.py
+ app
- __init__.py
- settings.py
- urls.py
+ static <-- notice the static directory.
+ templates
This is good of course for development where the Django server is the one serving these static files. In production you'll need to collect everything to the location declared in your STATIC_ROOT setting with the collectstatic management command.
This way you won't need to change the location each time you copy your project to a new location or a new computer.
Of course, that once you do that you can drop the STATICFILES_DIRS definition from your settings.py. This setting is used to tell Django that there are other static assets that reside outside of a certain app. If you want to use it anyway then you can define those directories relative to the project itself, i.e.:
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static")
)
Your urls.py should then use the staticfiles_urlpatterns like this:
if settings.DEBUG:
urlpatterns += staticfiles_urlpatterns()
For more information see the Django documentation on static files:
https://docs.djangoproject.com/en/1.7/howto/static-files/
I just figured out the solution for my question. First you need to get the current working directory and then for looking out for the folder in that current working directory(where your project is being installed) assign this to variable say path_for_images and then pass it to the STATICFILES_DIR as shown below:
path_for_images = os.getcwd()+"\static"
STATICFILES_DIRS = ( path_for images,) <-- note ,(comma) after `path_for_images`
No need to do any changes for the urls.py and images get loaded. This isn't exact pythonic way but it's surely one of the way.

How to compress a specific file using pipeline in Django?

I have many CSS files inside SITE_ROOT/sources/css and I want to compress only one file in SITE_ROOT/static/css using django-pipeline.
STATIC_ROOT = os.path.join(SITE_ROOT, 'static')
STATICFILES_DIRS = (
os.path.join(SITE_ROOT, 'sources'),
)
PIPELINE_CSS = {
'responsive': {
'source_filenames': (
'css/smartphones.css',
'css/tablets.css',
),
'output_filename': 'css/responsive.min.css',
}
}
After running collectstatic I see in the static/ folder the minified file (responsive.min.css) but there is also a copy of all files located in the sources/ folder and a copy of django admin static files.
How can I get only the minified file in the STATIC_ROOT folder?
You can create your own STATICFILES_STORAGE class, inherited from PipelineStorage, which expand the behavior of PipelineMixin. Something like this (need to be tested):
import shutil
import os.path
from django.conf import settings
from pipeline.storage import PipelineStorage
class PipelineCleanerStorage(PipelineStorage):
def post_process(self, paths, dry_run=False, **options):
# Do the usual stuff (compress and deliver)
res = PipelineStorage.post_process(self, paths, dry_run=False, **options)
# Clean sources files there
shutil.rmtree(os.path.join(settings.BASE_DIR, "static/sources"))
yield res
and use it in your settings.py instead of PipelineStorage.
Another way could be to run an automated task to clean this directory after each collectstatic. It would be the same idea but on the manage command itself.

django ImageField not uploading the file

So i've been googling this issue for the past hour and can't come up with a solution. Basically this is it: in my model.py i have a class that has this
class Case(models.Model):
zoomOutImage = models.ImageField('Label', upload_to="zoomOutImage")
and in my settings.py i have my media URL/ROOT set up like this
MEDIA_ROOT = os.path.join(os.path.abspath(''),'app/static/ds/')
MEDIA_URL = '/static/ds/'
which from the webserver should serve out like this:
http://127.0.0.1:8000/static/ds/zoomOutImage/actinic_granuloma_3.jpg
I've installed PIL (inside virtualENV) and there are no errors in uploading, the only issue is when i try uploading the file via the admin panel nothing happens. No errors nothing. The file just simply doesn't get uploaded to the zoomOutImage folder by the development server. Can anyone point me towards why?
I guess your file is in a subdir of your root, subdir named 'zoomOutImage'. Or even a file called like that in the root. I remember putting a function call in the upload to string. That function creates a path and filename, using os.join and the filename from the instance. Doing this by head, no example code available right now. But must be able to google this.
Look here https://stackoverflow.com/questions/1190697/django-filefield-with-upload-to-determined-at-runtime
And by the way, I totally disagree with your answer, you should NEVER use absolute paths in your settings! See this answer use css in django 1.4 development for how to use the correct settings and refer to your Project PATH
EDIT (after reading your own answer)
Guess you are missing this first step:
this is the path to your settings.py file:
SETTINGS_DIR = os.path.dirname(os.path.realpath(__file__))
and than this is the path to your project dir: (I Am using buildout, so call it buildout, but it's the root of your project):
BUILDOUT_DIR = os.path.abspath(os.path.join(SETTINGS_DIR, '..'))
and from there on you can define everything you want:
STATIC_ROOT = os.path.join(BUILDOUT_DIR, 'var', 'static')
STATIC_URL = '/static_media/'
MEDIA_ROOT = os.path.join(BUILDOUT_DIR, 'var', 'media')
MEDIA_URL = '/media/'
and in your template file refer to the image like:
<img src="{{MEDIA_URL}}{{ case.zoomOutImage }}" width="100%">
when your object given to the template is called case
about your question of the urls.
you should add this:
if settings.DEBUG:
urlpatterns += patterns('',
(r'', include('staticfiles.urls')),
)
and see the link above to the question about using css, it's the same problem, but there for finding the css files during development. It's all about the static file places.
import os
# get abspath
def rel(*x):
return os.path.join(os.path.abspath(os.path.dirname(__file__)), *x)
MEDIA_ROOT = rel('media')
MEDIA_URL = '/media/'
STATIC_URL = '/static/'
STATIC_ROOT = '' #if only your static files are in project folder
STATICFILES_DIRS = ( rel('static'),) #if only your static files are in project folder
use this settings, and everything will work
so i finally solved my problem. For anyone having this issue in the future do the following:
if you're trying to serve static media files locally on the development server use absolute paths for MEDIA_ROOT and MEDIA_URL.

Categories

Resources