错误消息:未配置DjangoTemplates后端

2024-06-25 07:27:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我是一个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.
>>>

==================  ==模板。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我五、六年前得到的===

 <!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>

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

Results in browser (I got 5 years ago)

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
===========

Tags: ofdjangoinpydividtitlehtml
1条回答
网友
1楼 · 发布于 2024-06-25 07:27:07

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

==之前:错误消息“未配置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

相关问题 更多 >