获取werkzeug.routing.BuildError

时间:2014-07-12 23:14:21

标签: python python-2.7 flask

当我去我的" login.html"时,我得到了一个werkzeug.routing.BuildError。页。问题似乎是" action ="模板中的属性。最初是action={{url_for('login')}}。虽然docs show it done this way它似乎不起作用。当我将其更改为action="/login"action="#"时,它可以正常工作。问题是为什么?我认为正确的方法是action={{url_for('login')}}

在我将代码分解成包(单个py文件中的所有内容)之前,它正常工作。

BTW,大部分代码来自Miguel Grindberg的伟大着作" Flask Web Development"。我遇到问题的代码是我自己的代码。我在WinXP上使用最新的Flask。以下是我的代码:

flasky\app\main\views.py

from flask import render_template, session, redirect, url_for, current_app, flash
from .. import db
from ..models import User
from ..email import send_email, post_mail
from . import main
from .forms import NameForm, RegForm


@main.route('/login', methods=['GET', 'POST'])
def login():
    form = RegForm()
    if form.validate_on_submit():
        session['name'] = form.username.data
        session['logged_in'] = True
        return redirect(url_for('success'))
    return render_template('login.html', form=form)

flasky\app\templates\login.html

{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}

{% block title %}Sign Up{% endblock %}


{% block content %}
    {{ super() }}

    <div class="well">
        <h1 align="center">Sign-In</h1>
    </div>

    <div class="container"> 
        <form class="form form-horizontal" action="{{url_for('login')}}" method="post">
            {{form.hidden_tag()}}

            {{wtf.form_field(form.username)}}

            {{wtf.form_field(form.email)}}

            {{wtf.form_field(form.password)}}

            {{wtf.form_field(form.bool)}}

            {{wtf.form_field(form.submit)}}
        </form>
    </div>  
{% endblock %}

<!-- action= {{url_for('login')}} doesn't work. . ."#" and "\login" work-->

flasky\app\main\forms.py

from flask.ext.wtf import Form
from wtforms import StringField, SubmitField, PasswordField, BooleanField, SubmitField
from wtforms.validators import Required, Email

class RegForm(Form):
    username = StringField('Username', validators=[Required()])
    email = StringField('Email Address', validators=[Email()])
    password = PasswordField('Password', validators=[Required()])
    bool = BooleanField("I Agree To Your Terms of Services", validators=[Required()])
    submit = SubmitField('Submit')

1 个答案:

答案 0 :(得分:8)

BuildError方法找不到符合描述的端点时,会引发url_for()。在这种情况下,未发现在Flask login对象中注册了app个端点。

您似乎已使用名为login蓝图注册main路线;您需要在端点名称中使用蓝图名称:

{{ url_for('main.login') }}

如果模板仅被main蓝图中的路径使用,您可以通过使用.启动名称来使其相对:

{{ url_for('.login') }}

请参阅蓝图文档的Building URLs section