Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error when using django.template

I'm a beginner in django and I got a lot of errors when using template module from django. The following works from the python shell:

from django import template
t = template.Template('My name is {{ name }}.')

When i use this code , i get the following error:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/site-packages/django/template/base.py", line 123, in __init__
 if settings.TEMPLATE_DEBUG and origin is None:
File "/usr/lib/python2.7/site-packages/django/conf/__init__.py", line 53, in __getattr__
self._setup(name)
File "/usr/lib/python2.7/site-packages/django/conf/__init__.py", line 46, in _setup
% (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting TEMPLATE_DEBUG,but        
settings are not configured. You must either define the environment variable 
DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

Dose anyone have an idea about this error?

like image 217
DearPython Avatar asked Aug 06 '13 13:08

DearPython


People also ask

What is server Error 500 in Django?

When DEBUG is False , Django will email the users listed in the ADMINS setting whenever your code raises an unhandled exception and results in an internal server error (strictly speaking, for any response with an HTTP status code of 500 or greater). This gives the administrators immediate notification of any errors.

How do I run a Django template?

To configure the Django template system, go to the settings.py file and update the DIRS to the path of the templates folder. Generally, the templates folder is created and kept in the sample directory where manage.py lives. This templates folder contains all the templates you will create in different Django Apps.


2 Answers

You can't access and run django projects from python shell. Django doesn't know what project you want to work on.

You have to do one of these things:

1. python manage.py shell
2. Set DJANGO_SETTINGS_MODULE environment variable in your OS to mysite.settings
3. Use setup_environ in the python interpreter:
   from django.core.management import setup_environ
   from mysite import settings
   setup_environ(settings)

The first one is easiest and best method. Run your code in the django shell.

like image 181
Sudipta Avatar answered Oct 20 '22 00:10

Sudipta


If you want to use the template system without the django shell, you can do:

from django.conf import settings
settings.configure()

and after this your code

t = template.Template('My name is {{ name }}.')
like image 16
Razvan Tudorica Avatar answered Oct 19 '22 23:10

Razvan Tudorica