简体   繁体   中英

Creating templates in Django / Python

I am learning Django and I tried to create a template like this:

>>> weekend = True
>>> from django.template import Template, Context
>>> template_string = """
{% if weekend %}
    <p> This is a weekend </p>
{% endif %}
"""
>>> t = Template(template_string)

I get this following error. Am I missing something?

Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    t = Template(template_string)
  File "C:\Python27\lib\site-packages\django\template\base.py", line 106, in __init__
    if settings.TEMPLATE_DEBUG and origin is None:
  File "C:\Python27\lib\site-packages\django\utils\functional.py", line 276, in __getattr__
    self._setup()
  File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 40, in _setup
    raise ImportError("Settings cannot be imported, because environment variable %s is undefined." % ENVIRONMENT_VARIABLE)
ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.

Thanks!

This has nothing to do with templates.

Start your shell by doing python manage.py shell from the directory containing manage.py and settings.py .

If you've started a django project try running the same code inside a django shell.

python manage.py shell

Alternatively set DJANGO_SETTINGS_MODULE to the name of your settings module. If you're using linux and running things from the directory where the settings.py file is then you can just do

export DJANGO_SETTINGS_MODULE="settings"

If you're using linux (or another unix based OS) and you want to run from a different directory you'll need to make sure your project directory is in the python path. Then you can do

export DJANGO_SETTINGS_MODULE="myapp.settings"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM