jinja2.exceptions.UndefinedError:' render_field'未定义

时间:2018-04-01 15:47:54

标签: python flask jinja2 wtforms

所以我刚开始将WtformsFlask结合使用,我设置了基本类并在forms.py中定义了我的所有字段,如此处所示......

from wtforms import Form, TextField, validators, PasswordField, DateField

class AddAccount(Form):
    username = TextField('Username', [validators.Length('min=3, max=20')])
    email = TextField('Email', [validators.Length('min=1, max=255')])
    karma = TextField('Karma', [validators.Length('min=1, max=10000000')])
    password = PasswordField('Password', [validators.Length('min=6, max=255')])

然后我将AddAccount课程导入views.py,您可以在此处看到...

from forms import AddAccount

@app.route('/dashboard/add', methods=['POST', 'GET'])
def add_account():

    form = AddAccount(request.form)

    if request.method == 'POST' and form.validate():
        print('POST request')


    return render_template('add_account.html', form=form)

这里是模板文件......

{% extends 'layout.html' %}

{% block body %}
    <br>
    <div class="jumbotron text-center">
       <h1>Add an Account</h1>
       <hr>
       <form action="{{url_for('add_account')}}">
            <div class="form-group">
                {{render_field(form.username, class_='form-control')}}
            </div>
            <div class="form-group">
                {{render_field(form.email, class_='form-control')}}    
            </div>
            <div class="form-group">
                {{render_field(form.password, class_='form-control')}}
            </div>
            <div class="form-group">
                {{render_field(form.karma, class_='form-control')}}
            </div>
        </form>
    </div>
{% endblock %}

整个装置导致此错误jinja2.exceptions.UndefinedError: 'render_field' is undefined,我完全不知道它为什么会发生或如何解决它。任何帮助将不胜感激。

如果它有帮助......这里是堆栈跟踪...

Traceback (most recent call last):
  File "C:\Users\Hassan\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 1997, in __call__
    return self.wsgi_app(environ, start_response)
  File "C:\Users\Hassan\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 1985, in wsgi_app
    response = self.handle_exception(e)
  File "C:\Users\Hassan\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 1540, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\Hassan\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\_compat.py", line 33, in reraise
    raise value
  File "C:\Users\Hassan\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 1982, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Users\Hassan\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 1614, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Users\Hassan\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 1517, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\Hassan\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\_compat.py", line 33, in reraise
    raise value
  File "C:\Users\Hassan\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 1612, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Users\Hassan\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\app.py", line 1598, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "E:\Python\manager\views.py", line 37, in add_account
    return render_template('add_account.html', form=form)
  File "C:\Users\Hassan\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\templating.py", line 134, in render_template
    context, ctx.app)
  File "C:\Users\Hassan\AppData\Local\Programs\Python\Python36\lib\site-packages\flask\templating.py", line 116, in _render
    rv = template.render(context)
  File "C:\Users\Hassan\AppData\Local\Programs\Python\Python36\lib\site-packages\jinja2\asyncsupport.py", line 76, in render
    return original_render(self, *args, **kwargs)
  File "C:\Users\Hassan\AppData\Local\Programs\Python\Python36\lib\site-packages\jinja2\environment.py", line 1008, in render
    return self.environment.handle_exception(exc_info, True)
  File "C:\Users\Hassan\AppData\Local\Programs\Python\Python36\lib\site-packages\jinja2\environment.py", line 780, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\Hassan\AppData\Local\Programs\Python\Python36\lib\site-packages\jinja2\_compat.py", line 37, in reraise
    raise value.with_traceback(tb)
  File "E:\Python\manager\templates\add_account.html", line 1, in top-level template code
    {% extends 'layout.html' %}
  File "E:\Python\manager\templates\layout.html", line 22, in top-level template code
    {% block body %}{% endblock %}
  File "E:\Python\manager\templates\add_account.html", line 10, in block "body"
    {{render_field(form.username, class_='form-control')}}
jinja2.exceptions.UndefinedError: 'render_field' is undefined

4 个答案:

答案 0 :(得分:1)

为什么你认为render_field功能?有关此的任何参考,您正在阅读哪些文档?无论如何,这应该可以解决问题:

{% extends 'layout.html' %}

{% block body %}
    <br>
    <div class="jumbotron text-center">
       <h1>Add an Account</h1>
       <hr>
       <form action="{{url_for('add_account')}}">
            <div class="form-group">
                {{form.username(class_='form-control')}}
            </div>
            <div class="form-group">
                {{form.email(class_='form-control')}}    
            </div>
            <div class="form-group">
                {{form.password(class_='form-control')}}
            </div>
            <div class="form-group">
                {{form.karma(class_='form-control')}}
            </div>
        </form>
    </div>
{% endblock %}

另见Add a css class to a field in wtform

答案 1 :(得分:1)

  1. 您需要创建部分文件,例如_formhelpers.html。
  2. 转到this link并复制“模板中的表单”代码,并将其粘贴到您创建的_formhelpers.html中
  3. 在模板文件中添加此行代码
{% from '_formhelpers.html' import render_field %}

答案 2 :(得分:0)

您可能会创建一个新文件,名为_formhelpers.html,内容为

{% macro render_field(field) %}
  <dt>{{ field.label }}
  <dd>{{ field(**kwargs)|safe }}
  {% if field.errors %}
    <ul class=errors>
    {% for error in field.errors %}
      <li>{{ error }}</li>
    {% endfor %}
    </ul>
  {% endif %}
  </dd>
{% endmacro %}

然后,在将表单加载到VIEW之前添加相同的内容

{% block body %}
<h1>Register </h1>
{% from '/includes/_formhelpers.html' import render_field %}
<form method="POST" action="">
    <div class="form-group">
        {{render_field(form.name ,class_="form-control")}}
    </div>
    <p><input type="submit" class="btn btn-primary" value="Submit"></p>
</form>

这应该可以为您解决问题。谢谢!

可以找到文档here

答案 3 :(得分:-2)

您必须使用此代码:

[
    {
        'adress': {
            'city': 'riga', 
            'country': 'latvia'
        },
        'org': {
            'iden': {
                'account': 'account123', 
                'id': 'id123'
            }
        },
        'person': {
            'birthYear': 1990,
            'gender': 'female',
            'name': {
                'fullname': 'laura'
            }
        },
        'subs': {
            'id': 'subs123',
            'org': {
                'buyer': {
                    'email': {
                        'address': 'email1@myorg.com|email2@sanoma.com'
                    },
                    'phone': {
                        'number': 371401234567
                    }
                }
            },
            'subs1': {
                'birthday': '1990-12-14T00:00:00Z',
                'org': {
                    'address': {
                        'country': 'latvia',
                        'strret1': 'street 1'
                    }
                }
            }
        }
    },
    {
        'adress': {
            'city': 'riga', 
            'country': 'latvia'
        },
        'org': {
            'iden': {
                'account': 'account123', 
                'id': 'id000'
            }
        },
        'person': {
            'birthYear': 1990,
            'gender': 'female',
            'name': {
                'fullname': 'laura'
            }
        },
        'subs': {
            'id': 'subs456',
            'org': {
                'buyer': {
                    'email': {
                        'address': 'email1@myorg.com'
                    },
                    'phone': {
                        'number': 371407654321
                    }
                }
            },
            'subs1': {
                'birthday': '1990-12-14T00:00:00Z',
                'org': {
                    'address': {
                        'country': 'latvia',
                        'strret1': 'street 1'
                    }
                }
            }
        }
    },
    {
        'adress': {
            'city': 'riga', 
            'country': 'latvia'
        },
        'org': {
            'iden': {
                'account': 'account123', 
                'id': 'id456'
            }
        },
        'person': {
            'birthYear': 1990,
            'gender': 'female',
            'name': {
                'fullname': 'laura'
            }
        },
        'subs': {
            'id': 'subs789',
            'org': {
                'buyer': {
                    'email': {
                        'address': 'email1@myorg.com'
                    },
                    'phone': {
                        'number': 371407654321
                    }
                }
            },
            'subs1': {
                'birthday': '1990-12-14T00:00:00Z',
                'org': {
                    'address': {
                        'country': 'latvia',
                        'strret1': 'street 1'
                    }
                }
            }
        }
    }
]

用于模板文件。

或者您可以包含 _fromhelpers.html。