首页 > 解决方案 > 错误消息:没有配置 DjangoTemplates 后端

问题描述

我是一个很老的人,5-6 年前使用了一点 Django。一位朋友帮助我开发了一个满足我需求的小程序,该工具的灵活性给我留下了深刻的印象。一年后,不再需要,所以我停止使用它。

今天,回到 Django,我花了一天时间了解如何在 Windows 10 上重新安装 Python 和 Django,并使用我用于学习的不同旧代码(学校案例练习效果很好)测试了 Django。我仍然有文件(代码、模板、输入和输出),但我收到一条错误消息。我想此消息可能来自语法更改(新版本??)或不完整的安装。有关信息,我从 Notepad++ 运行我的程序。

我不明白为什么错误消息是指像“base.py”这样的文件。

对于专家来说,解决问题可能很容易,但对我来说,这就像攀登珠穆朗玛峰。因此,如果有人有想法,我将不胜感激。非常感谢

为了提供帮助,我准备了一些资料。

1/

 - _ code
   _ errors messages (at running)
   _ template
   _ input
   _ output (I got before)

2/

 - _ Installation of Python and Django (commands I used)

非常感谢你的帮助 !

1/.....==== ==== 代码(文件:main.py)====

from django.conf import settings                # Don't be bothered by it
from django.template import Template, Context   # Don't be bothered by it
import data

with open(data.PICS_FILE, 'r', encoding='iso8859') as f:
    content = f.read()   # content will be a string

lines = content.split('\n')[0:-1]    ## \n: Newline character
finals = list(map(lambda line: line.split('\t')[0:-1], lines))  # we export the spreadsheet as a TAB-delimited file

list_dict = []

## finals[0]
for final in finals[1:]:
    d = {
        finals[0][0]: final[0],  # finals[0][0]: zeroth row, zeroth column
        finals[0][1]: final[1],
        finals[0][2]: final[2],
        finals[0][3]: final[3],
        finals[0][4]: final[4],
#        finals[0][5]: final[5],
#        finals[0][6]: final[6],
    }
    list_dict.append(d)

data.DATA['pics'] = list_dict

print(data.DATA)

with open('template.html', 'r') as f:
    template_str = f.read()

settings.configure()       # Set-up Django before using its functionalities
t = Template(template_str) # Django Template object
c = Context(data.DATA)     # Django Context object
final_html = t.render(c)   # returns a Python string

#strs = map(lambda d: template_str % d, list_dict)
#final_html = '\n\n'.join(strs)

with open('output.html', 'w', encoding='utf-8') as f:
    f.write(final_html)

=============

=== 运行 (main.py) 和错误消息 ====

Python 3.7.7 (tags/v3.7.7:d7c567b08f, Mar 10 2020, 10:41:24) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> 
============ RESTART: F:\recherche code Python\test_meeting3\main.py ===========
{'title': 'Excellent ! Félicitations ! ', 'titleNote': "I deleted comment11 et comment12 ('Empty' ,nothing in cell, in  pics.txt)", 'commentBottom1': 'Ceci est un nouveau commentaire', 'commentBottom2': 'Nouveau comment2', 'pics': [{'comment1': '', 'comment2': '', 'linkext': 'pict/nopict.png', 'linklocal': 'pict/nopict.png', 'comment3': "comment31éùÉê'est"}, {'comment1': 'Ceci est mon commentaire :', 'comment2': 'Le programme fonctionne bien', 'linkext': 'http://amolife.com/image/images/stories/beautiful%20birds/beautiful-birds-1.jpg', 'linklocal': 'pict/pict8.jpg', 'comment3': "comment32éùÉê'est"}, {'comment1': "comment13éùÉê'est", 'comment2': "comment23éùÉê'est", 'linkext': 'http://www.google.ca/imgres?imgurl=http%3A%2F%2Fstatic.squarespace.com%2Fstatic%2F50392129c4aa2c5a0b86bd15%2F50392129c4aa2c5a0b86bd27%2F5039251ac4aa2c5a0b86c275%2F1345922330960%2Fcbm1.jpeg&imgrefurl=http%3A%2F%2Fwww.companionbirdsministries.com%2F&h=300&w=590&tbnid=Kc0MRAGD30P6SM%3A&zoom=1&docid=DRtvtVIYyeX4UM&ei=KhmeVJynN8qiyASVx4KoAw&tbm=isch&ved=0CCQQMygJMAk&iact=rc&uact=3&dur=1581&page=1&start=0&ndsp=15', 'linklocal': 'pict/pict9.jpg', 'comment3': "comment33éùÉê'est"}]}
Traceback (most recent call last):
  File "F:\recherche code Python\test_meeting3\main.py", line 37, in <module>
    t = Template(template_str) # Django Template object
  File "C:\Python37\lib\site-packages\django\template\base.py", line 149, in __init__
    engine = Engine.get_default()
  File "C:\Python37\lib\site-packages\django\template\engine.py", line 79, in get_default
    raise ImproperlyConfigured('No DjangoTemplates backend is configured.')
django.core.exceptions.ImproperlyConfigured: No DjangoTemplates backend is configured.
>>>

========= ===template.html===

<!DOCTYPE html>
<html lang="eng">
<head id="page_header">
                <title>Test Python</title>
                <meta charset="utf-8"/>
                <link href="exo_test.css" rel="stylesheet" type="text/css" />

</head>
<body >
<!-- id_title -->
<div id="id_title">
        <!-- id_title_up -->
        <div id="id_title_up" align="left" >
                <h2 >
                {{ title }}</BR>
                </h2>
                <a><font size="2" color="white">
                {{ titleNote }}    </BR></font>
        </div>
<!-- End id_title_up -->
</div>

<!-- frame for displaying pict -->
<div id="id_frame_pict">
  <!-- n pict -->
  {% for pic in pics %}
<pre> {{ pic.comment1 }}
 {{ pic.comment2 }}
    <a href="{{ pic.linkext }}" target="blank"><img src="{{ pic.linklocal }}" width="50" alt="No pict"/></a><span style="color: #5500ff;">   {{ pic.comment3 }}</span></pre>
    <a>----------------------------------------------------------</a>
  {% endfor %}
<!-- end of n pict-->
</div>
<!-- en of frame for displaying pict --
<!--%%%%% Comment end of page %%%%%%%%-->
<div id="id_frame_bottom">
                <a><font size="3" color="red">
                {{ commentBottom1 }}    </BR></font>
                <a><font size="2" color="grey">
                {{ commentBottom2 }}    </BR></font>
<!--%% End of comment end of page %%-->
</div>
</body>
</html>

====== ==== output.html 我在 5 或 6 年前得到的===

 <!DOCTYPE html>
<html lang="eng">
<head id="page_header">
                <title>Test Python</title>
                <meta charset="utf-8"/>
                <link href="exo_test.css" rel="stylesheet" type="text/css" />

</head>
<body >
<!-- id_title -->
<div id="id_title">
        <!-- id_title_up -->
        <div id="id_title_up" align="left" >
                <h2 >
                Excellent ! Félicitations ! </BR>
                </h2>
                <a><font size="2" color="white">
                I deleted comment11 et comment12 (&#39;Empty&#39; ,nothing in cell, in  pics.txt)    </BR></font>
        </div>
<!-- End id_title_up -->
</div>

<!-- frame for displaying pict -->
<div id="id_frame_pict">
  <!-- n pict -->

<pre> 

    <a href="pict/nopict.png" target="blank"><img src="pict/nopict.png" width="50" alt="No pict"/></a><span style="color: #5500ff;">   comment31éùÉê&#39;est</span></pre>
    <a>----------------------------------------------------------</a>

<pre> Ceci est mon commentaire :
 Le programme fonctionne bien
    <a href="http://amolife.com/image/images/stories/beautiful%20birds/beautiful-birds-1.jpg" target="blank"><img src="pict/pict8.jpg" width="50" alt="No pict"/></a><span style="color: #5500ff;">   comment32éùÉê&#39;est</span></pre>
    <a>----------------------------------------------------------</a>

<pre> comment13éùÉê&#39;est
 comment23éùÉê&#39;est
    <a href="http://www.google.ca/imgres?imgurl=http%3A%2F%2Fstatic.squarespace.com%2Fstatic%2F50392129c4aa2c5a0b86bd15%2F50392129c4aa2c5a0b86bd27%2F5039251ac4aa2c5a0b86c275%2F1345922330960%2Fcbm1.jpeg&amp;imgrefurl=http%3A%2F%2Fwww.companionbirdsministries.com%2F&amp;h=300&amp;w=590&amp;tbnid=Kc0MRAGD30P6SM%3A&amp;zoom=1&amp;docid=DRtvtVIYyeX4UM&amp;ei=KhmeVJynN8qiyASVx4KoAw&amp;tbm=isch&amp;ved=0CCQQMygJMAk&amp;iact=rc&amp;uact=3&amp;dur=1581&amp;page=1&amp;start=0&amp;ndsp=15" target="blank"><img src="pict/pict9.jpg" width="50" alt="No pict"/></a><span style="color: #5500ff;">   comment33éùÉê&#39;est</span></pre>
    <a>----------------------------------------------------------</a>

<!-- end of n pict-->
</div>
<!-- en of frame for displaying pict --
<!--%%%%% Comment end of page %%%%%%%%-->
<div id="id_frame_bottom">
                <a><font size="3" color="red">
                Ceci est un nouveau commentaire    </BR></font>
                <a><font size="2" color="grey">
                Nouveau comment2    </BR></font>
<!--%% End of comment end of page %%-->
</div>
</body>
</html>

============ 

浏览器中的结果(我在 5 年前得到)

2/ Windows 10 安装 ===== W10- Python 和 Django****

 =======================
    Python installation :
    Download installer : https://www.python.org/downloads/
    Install Python 
       double-clicking on the downloaded file and following the installation prompts
          Check the box labeled "Add Python to PATH"
          "Choose installation"
              check : all users
              C:\Python37
    cmd :
    (version installée)
    py -3 -V   
    (install virtual environment tool)
    pip3 install virtualenvwrapper-win 
    (create a virtual environment for Django)
    mkvirtualenv dev-wp 
    (activate virtal environment)
    workon dev-wp 
                deactivate — Exit out of the current Python virtual environment
                workon — List available virtual environments
                workon name_of_environment — Activate the specified Python virtual environment
                rmvirtualenv name_of_environment — Remove the specified environment. 
    Install Django :
    pip3 install django
    check installation :
    py -m django --version (or : py -3 -m django --version )

    ===================== 
    project :
    =========== 
    create a folder :
    mkdir quiz-pq
    cd quiz-pq

    ===========
    launch Python from notepad++ :
    run --> path :   C:\Python37\Lib\idlelib\idle.py "$(FULL_CURRENT_PATH)"
    (Ctrl + shift + arrow right)

    -- error : from django.conf : no module named 'django'===? 
    sous cmd : 

    C:\Users\user1>pip freeze
    appdirs==1.4.3
    distlib==0.3.0
    filelock==3.0.12
    importlib-metadata==1.6.0
    six==1.14.0
    virtualenv==20.0.17
    virtualenvwrapper-win==1.2.6
    zipp==3.1.0

    C:\Users\user1>python
    Python 3.7.7 (tags/v3.7.7:d7c567b08f, Mar 10 2020, 10:41:24) [MSC v.1900 64 bit (AMD64)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import django
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ModuleNotFoundError: No module named 'django'
    >>>
    ---- solution ------- 
    install Django :
    pip install django
    updgrade pip :
    python -m pip install --upgrade pip
    verify install : 
    django-admin --version
    verif install :
    C:\Users\user1>django-admin --version
    3.0.5
===========

标签: pythondjangoinstallation

解决方案


问题解决了。请参阅下面我的程序文件中的修改。再次感谢你的帮助 !

==== 之前:错误消息“没有配置 DjangoTemplates 后端。”====

settings.configure()       # Set-up Django before using its functionalities
django.setup()
t = Template(template_str) # Django Template object
c = Context(DATA)     # Django Context object
final_xml = t.render(c)   # returns a Python string

=== 工作后,Djangotemplates 后端已配置 ================

TEMPLATES = [                           # Setup Django templates backend 
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['/path/to/template'],
    }
]
settings.configure(TEMPLATES=TEMPLATES) 
django.setup()                          # Set-up Django before using its functionalities
t = Template(template_str)              # Django Template object
c = Context(DATA)                       # Django Context object
final_xml = t.render(c)                 # returns a Python string

推荐阅读