Django——模版Template報錯

來源:互聯網
上載者:User

標籤:des   style   color   使用   os   io   for   ar   

 

>>> from django.template import Template>>> t = Template("My name is {{ my_name }}.")Traceback (most recent call last):  File "C:\Python33\lib\site-packages\django\conf\__init__.py", line 38, in _setup    settings_module = os.environ[ENVIRONMENT_VARIABLE]  File "C:\Python33\lib\os.py", line 676, in __getitem__    raise KeyError(key) from NoneKeyError: ‘DJANGO_SETTINGS_MODULE‘ During handling of the above exception, another exception occurred: Traceback (most recent call last):  File "", line 1, in    t = Template("My name is {{ my_name }}.")  File "C:\Python33\lib\site-packages\django\template\base.py", line 123, in __init__    if settings.TEMPLATE_DEBUG and origin is None:  File "C:\Python33\lib\site-packages\django\conf\__init__.py", line 54, in __getattr__    self._setup(name)  File "C:\Python33\lib\site-packages\django\conf\__init__.py", line 47, 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. 解決方案一:

先匯入settings

>>> from django.conf import settings

>>> settings.configure()

>>> from django import template
>>> t = template.Template(‘My name is {{ name}}.‘)
>>> c = template.Context({‘name‘:‘yixiaohan‘})
>>> print t.render(c)
My name is yixiaohan.
>>> c = template.Context({‘name‘:‘xiaowangge‘})
>>> print t.render(c)
My name is xiaowangge.

解決方案二:

使用python manage.py shell啟動Python互動式解譯器(實際上啟動的是Ipython)

python manage.py shell

[email protected]:~/djbk$ python manage.py shell
Python 2.7.3 (default, Aug 1 2012, 05:16:07)
Type "copyright", "credits" or "license" for moreinformation.

IPython 0.12.1 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython‘sfeatures.
%quickref -> Quick reference.
help -> Python‘s own help system.
object? -> Details about ‘object‘, use ‘object??‘ for extradetails.

In [1]: from django import template

In [2]: t = template.Template("my name is {{ name}}")

In [3]: c = template.Context({‘name‘:‘yixiaohan‘})

In [4]: rt = t.render(c)

In [5]: rt
Out[5]: u‘my name is yixiaohan‘

In [6]: print rt
my name is yixiaohan

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.