Сообщение об ошибке: не настроен бэкэнд DjangoTemplates - PullRequest
0 голосов
/ 16 апреля 2020

Я довольно старый парень, который использовал немного Django 5-6 лет go. Друг помог мне разработать небольшую программу для моих нужд, и я был очень впечатлен гибкостью этого инструмента. Через 1 год больше не нужно, поэтому я перестал его использовать.

Сегодня, возвращаясь к Django, я провожу день, чтобы понять, как переустановить Python и Django на Windows 10. и я проверил 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)

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

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

<code><!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>
----------------------------------- ----------------------- {% endfor%} {{commentBottom1}} {{commentBottom2}}

====== ==== выход. html Я получил 5 или 6 лет назад ===

<code> <!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>
------------------------------------------------ ----------
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>
------------------------------- ---------------------------
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>
-------------- -------------------------------------------- Ceci est un nouveau commentaire Nouveau comment2 ============

Результаты в браузере (я получил 5 лет go)

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

1 Ответ

0 голосов
/ 18 апреля 2020

Проблема решена . Смотрите ниже модификацию в моем программном файле. Еще раз спасибо за вашу помощь!

==== До: сообщение об ошибке «Не настроен бэкэнд 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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...