首页 > 解决方案 > 重定向时出现烧瓶错误:TypeError: __init__() 采用 1 到 2 个位置参数,但给出了 3 个

问题描述

我是烧瓶的新手,我正在按照 youtube 上的教程https://www.youtube.com/watch?v=CSHx6eCkmv0&t=36s学习它。如果我运行以下代码并转到浏览器,它运行良好,但每当我希望网页重定向时就会出现错误。代码如下:

from flask import Flask, render_template, url_for, flash, redirect
from forms import RegistrationForm, LoginForm

app = Flask(__name__)

app.config['SECRET_KEY'] = '765bb2ad427608c76640cbec522eb8c2'

posts = [
    {
        'author': 'Takunda Mafuta',
        'title': 'Blog Post 1',
        'content': 'Content 1',
        'date_posted': '19 Jan 2020'
    },
    {
        'author': 'Thelma Mafuta',
        'title': 'Blog Post 2',
        'content': 'Content 2',
        'date_posted': '18 Jan 2020'
    }
]


@app.route('/')
@app.route('/home')
def home():
    return render_template('home.html', posts=posts)


@app.route('/about')
def about():
    return render_template('about.html', title='about')


@app.route("/register", methods=['GET', 'POST'])
def register():
    form = RegistrationForm()
    if form.validate_on_submit():
        flash(f'Account created for {form.username.data}!', 'success')
        return redirect(url_for('home'))
    return render_template('register.html', title='Register', form=form)


@app.route('/login')
def login():
    form = LoginForm()
    return render_template('login.html', title='Login', form=form)


if __name__ == '__main__':
    app.run(debug=True)

错误如下:

TypeError
TypeError: __init__() takes from 1 to 2 positional arguments but 3 were given

Traceback (most recent call last)
File "C:\Users\Takunda Mafuta\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 2463, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\Takunda Mafuta\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 2449, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\Takunda Mafuta\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1866, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\Takunda Mafuta\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Users\Takunda Mafuta\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 2446, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\Takunda Mafuta\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1951, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\Takunda Mafuta\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1820, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\Takunda Mafuta\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\_compat.py", line 39, in reraise
raise value
File "C:\Users\Takunda Mafuta\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1949, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\Takunda Mafuta\AppData\Local\Programs\Python\Python38-32\Lib\site-packages\flask\app.py", line 1935, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\Takunda Mafuta\Videos\lgT Personal Development\Data Science\Python\Tutorials\Flask Web Development\Flask-Demo\FlaskBlog\FlaskBlog.py", line 38, in register
if form.validate_on_submit():
File "C:\Users\Takunda Mafuta\AppData\Roaming\Python\Python38\site-packages\flask_wtf\form.py", line 101, in validate_on_submit
return self.is_submitted() and self.validate()
File "C:\Users\Takunda Mafuta\AppData\Roaming\Python\Python38\site-packages\wtforms\form.py", line 310, in validate
return super(Form, self).validate(extra)
File "C:\Users\Takunda Mafuta\AppData\Roaming\Python\Python38\site-packages\wtforms\form.py", line 152, in validate
if not field.validate(self, extra):
File "C:\Users\Takunda Mafuta\AppData\Roaming\Python\Python38\site-packages\wtforms\fields\core.py", line 206, in validate
stop_validation = self._run_validation_chain(form, chain)
File "C:\Users\Takunda Mafuta\AppData\Roaming\Python\Python38\site-packages\wtforms\fields\core.py", line 226, in _run_validation_chain
validator(form, self)
TypeError: __init__() takes from 1 to 2 positional arguments but 3 were given
The debugger caught an exception in your WSGI application. You can now look at the traceback which led to the error.
To switch between the interactive traceback and the plaintext one, you can click on the "Traceback" headline. From the text traceback you can also create a paste of it. For code execution mouse-over the frame you want to debug and click on the console icon on the right side.

You can execute arbitrary Python code in the stack frames and there are some extra helpers available for introspection:

dump() shows all variables in the frame
dump(obj) dumps all that's known about the object

报名表格代码:

  1. 项目清单

(一)forms.py

from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, BooleanField
from wtforms.validators import DataRequired, Length, Email, EqualTo


class RegistrationForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired(), Length(min=2, max=20)])
    email = StringField('Email', validators=[DataRequired, Email()])
    password = PasswordField('Password', validators=[DataRequired()])
    confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')])
    submit = SubmitField('Sign Up')


class LoginForm(FlaskForm):
    email = StringField('Email', validators=[DataRequired, Email()])
    password = PasswordField('Password', validators=[DataRequired()])
    remember = BooleanField('Remember Me')
    submit = SubmitField('Login')

(B) register.html

{% extends "layout.html" %}
{% block content %}
            <div class="content-section">
                <form method="POST" action="">
                    {{ form.hidden_tag() }}
                    <fieldset class="form-group">
                        <legend class="border-bottom mb-4">Join Today</legend>
                        <div class="form-group">
                            {{ form.username.label(class="form-control-label") }}
                            {{ form.username(class="form-control form-control-lg") }}
                        </div>
                        <div class="form-group">
                            {{ form.email.label(class="form-control-label") }}
                            {{ form.email(class="form-control form-control-lg") }}
                        </div>
                        <div class="form-group">
                            {{ form.password.label(class="form-control-label") }}
                            {{ form.password(class="form-control form-control-lg") }}
                        </div>
                        <div class="form-group">
                            {{ form.confirm_password.label(class="form-control-label") }}
                            {{ form.confirm_password(class="form-control form-control-lg") }}
                        </div>
                    </fieldset>
                    <div class="form-group">
                        {{ form.submit(class="btn btn-outline-info") }}
                    </div>
                </form>
            </div>
            <div class="border-top pt-3">
                <small class="text-muted">
                    Already Have An Account? <a class="ml-2" href="{{ url_for('login') }}">Sign In</a>
                </small>
            </div>
{% endblock content %}

我不确定这是否是错误的根源:似乎没有从烧瓶导入重定向的选项,而是从 django.shortcuts 和 werkzeug.utils 导入重定向。见附图。 导入重定向

标签: htmlpython-3.xflask

解决方案


推荐阅读