Django can't find template - Polls App Part 3 - python

I am following the polls app tutorial part 3 and I cannot get the templates to be found
This is the exact error
polls/index.html
Request Method: GET
Request URL: http://localhost:8000/polls/
Django Version: 1.4.3
Exception Type: TemplateDoesNotExist
Exception Value:
polls/index.html
Exception Location: c:\Python27\lib\site-packages\django\template\loader.py in find_template, line 138
Python Executable: c:\Python27\python.exe
Python Version: 2.7.2
So in my settings.py I have put the directory there. "C:/Scripts/mysite/template" and created /polls/index.html
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:/Scripts/template"
"C:/Scripts/mysite/template"
)
It for some reason cannot find it though. Any ideas?
This is the exact instruction from the tutorial.
create a directory, somewhere on your filesystem, whose contents Django can access. (Django runs as whatever user your server runs.)

You're missing a comma at the end of the first line:
"C:/Scripts/template", # <--- HERE
"C:/Scripts/mysite/template"
without that, Python automatically concatenates the two strings (because they're inside parens) so that it just becomes "C:/Scripts/templateC:/Scripts/mysite/template".

Debug
from your applications main folder, run the following command: python manage.py shell this is going to bootstrap your app with the settings file.
type from django.conf import settings and hit enter
type settings.TEMPLATE_DIRS and check the output. Do you see the template directories that you specified?
Absolute paths relative to the settings.py file
I generally use absolute paths relative to the settings.py file. That way collaborators can share a main settings file, and no matter what system/environment you deploy to your paths will be correct.
to do this:
# settings.py
import os
# ... other settings
TEMPLATE_DIRS = (
os.path.join(os.path.normpath(os.path.dirname(__file__)), 'templates'),
)
let me know if the debug step didn't help, and i'll try and supply some more help.

Related

Importing path to settings Django (django-rest-auth)

I am stuck with very trivial thing in Django, and that is I don't know how to define path to REGISTER_SERIALIZER in main settings file. I am using http://django-rest-auth.readthedocs.io/en/latest/configuration.html. I added all the apps, and it works without custom serializer. I just need to know how to add valid path this (you can check link for library example).
This is what I tried:
REST_AUTH_REGISTER_SERIALIZERS = {
'REGISTER_SERIALIZER' : os.path.join(BASE_DIR, "rest\\rest_user_profile\\serializers.RegisterSerializer")
}
the path is correct and still I get
ImportError: No module named 'C:\\...\\rest\\rest_user_profile\\serializers'

How to verify if django settings are applied correctly?

Let's say I have the following settings.py:
LOCALE_PATHS = (
'/conf/locale'
)
DEBUG = True
Can I read value of DEBUG from my python code?
Can I get full path to my language file (django.mo) django uses taken into consideration my LOCALE_PATHS value?
Yes, you can import settings and look for your values:
from django.conf import settings
print settings.DEBUG
Included in a separate comment was the following from LA_:
"Thanks, Joseph. If I print settings.LOCALE_PATHS, it prints exactly the value I defined. How could I get the full path django uses?"
What may be useful for you to do is record the absolute path by using the os.path module.
For example, you could do the following:
PROJECT_PATH = os.path.abspath(os.path.dirname(__file__))
LOCALE_ABS_PATH = os.path.join(PROJECT_PATH, LOCALE_PATHS[0])
Then you could reference LOCALE_ABS_PATH as the absolute path to the LOCALE_DIRS listed in settings.py
Let me know if this is helpful at all. I'm not entirely sure of the context with which you plan to implement that, but perhaps I could help more if you continue to have trouble.

Django: where do I call settings.configure?

The Django docs say that I can call settings.configure instead of having a DJANGO_SETTINGS_MODULE. I would like my website's project to do this. In what file should I put the call to settings.configure so that my settings will get configured at the right time?
Edit in response to Daniel Roseman's comment:
The reason I want to do this is that settings.configure lets you pass in the settings variables as a kwargs dict, e.g. {'INSTALLED_APPS': ..., 'TEMPLATE_DIRS': ..., ...}. This would allow my app's users to specify their settings in a dict, then pass that dict to a function in my app that augments it with certain settings necessary to make my app work, e.g. adding entries to INSTALLED_APPS.
What I envision looks like this. Let's call my app "rexe_app". In wsgi.py, my app's users would do:
import rexe_app
my_settings = {'INSTALLED_APPS': ('a','b'), ...}
updated_settings = rexe_app.augment_settings(my_settings)
# now updated_settings is {'INSTALLED_APPS': ('a','b','c'), 'SESSION_SAVE_EVERY_REQUEST': True, ...}
settings.configure(**updated_settings)
Its not quite equivalent, since settings DJANGO_SETTINGS_MODULE updates defaults, found in django.conf.settings.global_settings, while parameter for configure completely ignores them, so you have to add some additional processing.
Beware, first, that you can't modify INSTALLED_APPS on the fly, as they are examined once on settings processing. For example, to apply modifications to INSTALLED_APPS in Apache-deployed application, you need to restart Apache.
Second, as settings are imported, therefore this point is prone to injections of some sorts, and is highly vulnerable to expose them to users.
If this is a meta app, there are two possibilities:
If you want to provide default settings for `django`-wise setting, add following to `default_settings.py` in your app:
INSTALLED_APPS = ('default_app', )
Just make sure you don't import `default_settings.py` in your app, and make your users add to their settings.py
from rexe_app.default_settings import *
INSTALLED_APPS += ('users_app', )
that effectively will set `INSTALLED_APPS` to `('default_app', 'users_app', )` for your end users.
In case you need `rexe_app`-wise settings, you can default them in your app's `__init__.py`:
from django.conf import settings
REXE_APP_CONFIG_PARAM = getattr(settings, 'REXE_APP_CONFIG_PARAM',
'default_param_value')
so when user needs to change default `REXE_APP_CONFIG_PARAM` he needs to just add
INSTALLED_APPS = ('rexe_app')
REXE_APP_CONFIG_PARAM = 'user_param_value'
to his `settings.py`.
It would be in your wsgi script. please have look at the docs.
You could run mysite.settings.configure() instead of os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
If you are using wsgi then call that in your wsgi script before running the app.
If you want to do this for dev server, pass it as command line option (mentioned on the same page).
django-admin.py runserver --settings=mysite.settings

Bottlepy: template not found

I have server running on apache. I use bottle.py. When I'm going to xxx/getbio, SOMETIMES it returns :
Error: 500 Internal Server Error: Template 'bio' not found.
This error occurs not all time: if I restart apache, it's normalizing for several hours, but happens again. Here is code fragment :
#route('/getbio')
def getBio():
return template('bio')
Here is file structure :
xxx/
├── views/
│ ├── bio.tpl
└── index.py
And I didin't missed following lines of code:
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
sys.path.append('views')
os.chdir(os.path.dirname(os.path.abspath(__file__)))
Please help me, because I don't have idea how to fix this bug
Add your template location to TEMPLATE_DIR, not to sys.path:
bottle.TEMPLATE_PATH.insert(0, 'views')
You may find that it's more robust to use the absolute path:
bottle.TEMPLATE_PATH.insert(0, '/path/to/xxx/views')
By default Bottle adds the views folder to the template path for template files. However, at least on Windows, it looks for the views folder relative to where the python script was invoked from (ie. the current working directory) and not relative to where the app entry point .py file is found.
Therefore if your folder structure looks like this:
xxx/
├── views/
│ ├── bio.tpl
└── index.py
and index.py is your Bottle app entry point, you would need to launch index.py with xxx as the current working directory.
Hard-coding the path to the templates folder should work, but is not a portable solution.
You can however specify the absolute path to the templates folder in a portable way by determining it at runtime with code like this:
import os
abs_app_dir_path = os.path.dirname(os.path.realpath(__file__))
abs_views_path = os.path.join(abs_app_dir_path, 'views')
bottle.TEMPLATE_PATH.insert(0, abs_views_path )
Just change the line performing the os.path.join call to correctly construct the abs_views_path relative to your file.
This way, you can simply move the code from machine to machine, and run it from any working directory, and as long as your views folder location is always in the correct place relative to your app it will be found.
AFAIK, bottle has TEMPLATE_PATH constant to store template paths. Try to modify it in the case you want e.g:
from pathlib import Path
from bottle import TEMPLATE_PATH
TEMPLATE_PATH.append(str(Path('path') / 'to' / 'template'))
Then, path/to/template path will be included as one of template paths in your app.
Unfortunately Bottle have a bag in include () function
% include ("my_template.tpl") # template not found
% include("my_template.tpl") # template found
the only difference it is space after "include" is forbidden.
Hope this issue message will help somebody save time in debugging
https://github.com/bottlepy/bottle/issues/1258
And template have to be in bottle.TEMPLATE_PATH
bottle.TEMPLATE_PATH.insert(0, abs_views_path )
If you only pass one keyword argument to the template() function, it will be interpreted as the name of the template file. Example:
return template('<h3>Hello World!</h3>')
If you do not have a template file with the name of '<h3>Hello World!</h3>', you will get a template not found error.
Adding a substitution in the string, and keyword argument to the same line of code will cause Bottle to try and render the first argument as the template itself, instead of searching for it as a file.
return template('<h3>Hello, {{foobar}}</h3>', foobar='foobar')

Unusual warning with djcelery, billiard, and the django_settings_module

When running manage.py celeryd for async processes, everything works as expected but i'm getting a weird warning at every start-up. It's not causing any errors, but i'm having trouble making it disappear or understanding its meaning.
Here it is:
/home/user/lib/python2.7/billiard-2.7.3.15-py2.7-linux
-x86_64.egg/billiard/forking.py:455:
UserWarning: Will add directory '/home/user/webapps/django/proj' to path!
This is necessary to accommodate pre-Django 1.4 layouts using setup_environ.
You can skip this warning by adding a DJANGO_SETTINGS_MODULE=settings
environment variable.
W_OLD_DJANGO_LAYOUT % os.path.realpath(project_dir)
This is unusual because the django settings module has been added to my wsgi, and it works for everything but this. Does it want me to add the settings to httpd.conf or something?
Thanks
Oddly enough, I just ran into the same problem! Looking up the file in question (billiard/forking.py), I found this function:
def _Django_old_layout_hack__save():
if 'DJANGO_PROJECT_DIR' not in os.environ:
try:
settings_name = os.environ['DJANGO_SETTINGS_MODULE']
except KeyError:
return # not using Django.
try:
project_name, _ = settings_name.split('.', 1)
except ValueError:
return # not modified by setup_environ
project = __import__(project_name)
try:
project_dir = os.path.normpath(_module_parent_dir(project))
except AttributeError:
return # dynamically generated module (no __file__)
warnings.warn(UserWarning(
W_OLD_DJANGO_LAYOUT % os.path.realpath(project_dir)
))
os.environ['DJANGO_PROJECT_DIR'] = project_dir
This function apparently does some sanity checks on os.environ. Notice that, after retrieving DJANGO_SETTINGS_MODULE, it tries to split the module name by a period. This code seems to assume that, if your DJANGO_SETTINGS_MODULE is a top-level module (as it is, by default), then your environment hasn't been modified.
Unfortunately, if it isn't a top-level module, it seems to assume that you used setup_environ, and that it must now add the project directory to the path.
In my case, I had simply moved the simple settings.py module out into its own settings package, splitting it up into the common, and development/production files. Of course, I had to modify manage.py and wsgi.py to point to the correct settings module. Which, of course, started to trigger this warning.
The way I worked around it was by adding the DJANGO_PROJECT_DIR variable directly in my manage.py. I'm not sure if I'll need to add it elsewhere (e.g. in production environments), but that's all I've run into so far.
Here's the relevant line in manage.py:
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings.current")
# Add the project directory to the path, to appease billiard
os.environ.setdefault("DJANGO_PROJECT_DIR",
os.path.dirname(os.path.realpath(__file__)))
I'm using django 1.4 and celery 3.0.11.
thank's #voithos. I tried yours solution. It's work for me.
But I came across another solution, much more simple. no need of creating a new module settings.
Juste add this piece of code into your manage.py file
# Add the project directory to the path, to appease billiard
os.environ.setdefault("DJANGO_PROJECT_DIR", os.path.dirname(os.path.realpath(__file__)))
finally my manage.py file looks like this
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sample.settings")
from django.core.management import execute_from_command_line
# Add the project directory to the path, to appease billiard
os.environ.setdefault("DJANGO_PROJECT_DIR",os.path.dirname(os.path.realpath(__file__)))
execute_from_command_line(sys.argv)

Categories

Resources