简体   繁体   English

文件 ”<template> &quot;,第 1 行,在顶级模板代码 jinja2.exceptions.UndefinedError: &#39;Check&#39; 未定义

[英]File "<template>", line 1, in top-level template code jinja2.exceptions.UndefinedError: 'Check' is undefined

i want create data entry form using python GUI,if i run in terminal i got error massage like this :我想使用 python GUI 创建数据输入表单,如果我在终端中运行,我会得到这样的错误消息:

File "<template>", line 1, in top-level template code
jinja2.exceptions.UndefinedError: 'Check' is undefined

but if i run on debug mode i got message error like this:但是如果我在调试模式下运行,我会收到如下消息错误:

Exception has occurred: UndefinedError 'Check' is undefined

Here my code:这是我的代码:

import PySimpleGUI as sg
from pathlib import Path
import datetime
from docxtpl import DocxTemplate


dokumen_path = Path(__file__).parent / "word_template.docx"
doc = DocxTemplate(dokumen_path)

def tanggal_waktu():
    hari = datetime.datetime.today()
    return hari

layout = [
    [sg.Text("GUEST NAME"), sg.Input(key="NAMA", do_not_clear=False)],
    [sg.Text("CHECK-IN"), sg.Input(key="Check-in", do_not_clear=False)],
    [sg.Text("CHECK-OUT"), sg.Input(key="Check-out", do_not_clear=False)],
    [sg.Text("ROOM NO"), sg.Input(key="KAMAR",do_not_clear=False)],
    [sg.Text("TYPE"), sg.Input(key="TIPE",do_not_clear=False)],
    [sg.Text("PERSON"), sg.Input(key="ORANG", do_not_clear=False)],
    [sg.Text("ROOM CHARGE"), sg.Input(key="RC",do_not_clear=False),],
    [sg.Button("Submit"), sg.Exit()],
]

window = sg.Window("Invoice Palm Garden Guest House", layout, element_justification="right")

while True:
    event, values = window.read()
    if event == sg.WIN_CLOSED or event == "Exit":
        break
    if event == "Submit":
        print(values)
        values["D/T"] = tanggal_waktu()
        values["TOTAL"] = int(values["RC"])
        doc.render(values)
        output_path = Path(__file__).parent / f"{values['NAMA']}-Invoice.docx"
        doc.save(output_path)
        sg.popup("File Saved")
    else:
        pass


window.close()

Here my word template这是我的word模板

word template picture word模板图片

You are seeing this error it is because the jinja library is not able to render the variables defined in word_template.docx template.您看到此错误是因为 jinja 库无法呈现 word_template.docx 模板中定义的变量。 For example you need to change the variable such as {{D/T}} to {{ d_t }} or something meaningful name such as {{ time }} .例如,您需要将诸如{{D/T}}的变量更改为{{ d_t }}或诸如{{ time }}之类的有意义的名称。 You to read documentation of jinja2 variables definition https://jinja.palletsprojects.com/en/3.1.x/templates/ you can also define variables in this format您可以阅读 jinja2 变量定义文档https://jinja.palletsprojects.com/en/3.1.x/templates/您也可以以这种格式定义变量

{{ foo.bar }}
{{ foo['bar']}}

If you pass foo dictionary with key bar while rendering value of bar will be saved.如果你通过 foo 字典与键bar同时渲染 bar 的值将被保存。

Modified code: invoice_gui.py修改代码:invoice_gui.py

"""
invoice_gui.py
"""
import PySimpleGUI as sg
from pathlib import Path
import datetime
from docxtpl import DocxTemplate
import argparse


def tanggal_waktu():
    hari = datetime.datetime.today()
    return hari

layout = [
    [sg.Text("GUEST NAME"), sg.Input(key="name", do_not_clear=False)],
    [sg.Text("CHECK-IN"), sg.Input(key="check_in", do_not_clear=False)],
    [sg.Text("CHECK-OUT"), sg.Input(key="check_out", do_not_clear=False)],
    [sg.Text("ROOM NO"), sg.Input(key="room",do_not_clear=False)],
    [sg.Text("TYPE"), sg.Input(key="type",do_not_clear=False)],
    [sg.Text("PERSON"), sg.Input(key="person", do_not_clear=False)],
    [sg.Text("ROOM CHARGE"), sg.Input(key="rc",do_not_clear=False),],
    [sg.Button("Submit"), sg.Exit()],
]

def main(args):
    template_name = args.name
    print('template_name: %s' % (template_name))
    dokumen_path = Path(__file__).parent / "{}".format(template_name)
    doc = DocxTemplate(dokumen_path)
    window = sg.Window("Invoice Palm Garden Guest House", layout, element_justification="right")
    while True:
        event, values = window.read()
        if event == sg.WIN_CLOSED or event == "Exit":
            break
        if event == "Submit":
            print(values)
            values["time"] = tanggal_waktu()
            values["total"] = int(values["rc"])
            doc.render(values)
            output_path = Path(__file__).parent / f"{values['name']}-Invoice.docx"
            doc.save(output_path)
            sg.popup("File Saved")
        else:
            pass
    window.close()

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Python GUI script for invoice generator')
    parser.add_argument('-n', '--name',
                        default='word_template.docx', help='Specify the file name of word_template. Default is `word_template.docx`')
    main(parser.parse_args())

How to run the code如何运行代码

python invoice_gui.py -n word_template.docx

Modified template with variables.带变量的修改模板。 在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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