Python Flask self.errors.append() - AttributeError: 'tuple' 对象没有属性 'append'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22889295/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:53:55  来源:igfitidea点击:

Flask self.errors.append() - AttributeError: 'tuple' object has no attribute 'append'

pythondjangoflaskflask-wtforms

提问by Max

My small registration app gives and error when I try to validate the submited data by user and check if the entered e-mail exists.

当我尝试验证用户提交的数据并检查输入的电子邮件是否存在时,我的小型注册应用程序出现错误。

here is my files:
forms:

这是我的文件:
表格:

from flask.ext.wtf import Form
from wtforms import TextField, BooleanField, PasswordField, TextAreaField, validators
from wtforms.validators import Required
from app import models

class RegisterForm(Form):
"""RegisterForm class needed for retrieving data from user"""
username = TextField('username', [validators.Length(min=3, max=50), validators.Required()])
email = TextField('email', [validators.Length(min=3, max=100), validators.Required()])
password = PasswordField('password', [validators.Required()])
age = TextField('age', [validators.Length(min=1, max=3), validators.Required()])
about_user = TextAreaField('about_user', [validators.Length(max=500)])
img_url = TextField('img_url')


def email_unique(self, email):
    if models.User.query.filter_by(email = email).first() != None:
        self.email.errors.append('This E-mail address is already in use. Please choose another one.') 
        return False

views:

意见:

#!flask/bin/python
from app import app, db, lm
from flask import render_template, url_for, flash, g, redirect, session, request
from flask.ext.login import login_user, logout_user, current_user, login_required
from forms import LoginForm, RegisterForm, EditForm
from models import User

@app.route('/register', methods = ['GET', 'POST'])
def register():
    form = RegisterForm()
    #makes the username unique
    u_unique =  form.username.data
    u_unique = User.unique_username(u_unique)

    #validates email adress and checks if it already exists or not 
    form.email_unique(form.email.data)

    if form.validate_on_submit():
        user = User(
            u_unique,
            form.password.data, 
            form.email.data, 
            form.age.data, 
            form.about_user.data,
            form.img_url.data)
        db.session.add(user)
        db.session.commit()
        flash('Thank you for your registration')
        flash('Your username is: ' + str(u_unique))
        return redirect(url_for('login'))
    else:
        for error in form.errors:
            flash(error)

    return render_template('register.html',
        title = 'Registeration',
        form = form)

The error is:

错误是:

Traceback (most recent call last) File <br> "/home/maksad/Desktop/faskMonkey/flask/lib/python2.7/site-packages/flask/app.py", line 1701, in __call__ return self.wsgi_app(environ, start_response) 
File "/home/maksad/Desktop/faskMonkey/flask/lib/python2.7/site-packages/flask/app.py", line 1689, in wsgi_app response = self.make_response(self.handle_exception(e)) 
File "/home/maksad/Desktop/faskMonkey/flask/lib/python2.7/site-packages/flask/app.py", line 1687, in wsgi_app response = self.full_dispatch_request() 
File "/home/maksad/Desktop/faskMonkey/flask/lib/python2.7/site-packages/flask/app.py", line 1360, in full_dispatch_request rv = self.handle_user_exception(e) 
File "/home/maksad/Desktop/faskMonkey/flask/lib/python2.7/site-packages/flask/app.py", line 1358, in full_dispatch_request rv = self.dispatch_request() 
File "/home/maksad/Desktop/faskMonkey/flask/lib/python2.7/site-packages/flask/app.py", line 1344, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) 
File "/home/maksad/Desktop/faskMonkey/app/views.py", line 92, in register form.email_unique(form.email.data) 
File "/home/maksad/Desktop/faskMonkey/app/forms.py", line 26, in email_unique
 self.email.errors.append('This E-mail address is already in use. Please choose another one.')
 AttributeError: 'tuple' object has no attribute 'append'

采纳答案by A.J. Uppal

The tupleobjects cannot append. Instead, convert to a list using list(), and append, and then convert back, as such:

tuple对象不能追加。相反,使用list(), 和 append转换为列表,然后转换回来,如下所示:

>>> obj1 = (6, 1, 2, 6, 3)
>>> obj2 = list(obj1) #Convert to list
>>> obj2.append(8)
>>> print obj2
[6, 1, 2, 6, 3, 8]
>>> obj1 = tuple(obj2) #Convert back to tuple
>>> print obj1
(6, 1, 2, 6, 3, 8)

Hope this helps!

希望这可以帮助!

回答by sshashank124

tuplesare immutable types which means that you cannot splice and assign values to them. If you are going to be working with data types where you need to add values and remove values, use list instead:

tuples是不可变的类型,这意味着您不能对它们进行拼接和赋值。如果您要使用需要添加值和删除值的数据类型,请改用列表:

>>> a = (1,2,3)
>>> a.append(2)
AttributeError: 'tuple' object has no attribute 'append'
>>> b = [1,2,3]
>>> b.append(2)
[1,2,3,2]

回答by 24HourPhysicist

Just came across this myself. I think a better answer to your question is that you should validate the elements before you add errors to them. The validation process sets the error field to a list and if you change it before you validate fields it will be written over when you validate.

刚刚自己遇到了这个。我认为对您的问题更好的答案是,您应该在向元素添加错误之前验证元素。验证过程将错误字段设置为一个列表,如果您在验证字段之前更改它,它将在您验证时被覆盖。

So override the validate method of your form, call the parent validate method then run your email_unique method in that.

因此,覆盖表单的验证方法,调用父验证方法,然后在其中运行您的 email_unique 方法。

Then you can remove the email_unique from the view since it will be part of your validate_on_submit

然后您可以从视图中删除 email_unique,因为它将成为您的 validate_on_submit 的一部分

回答by Zaytsev Dmitry

The answer is a bit deeper. "errors" is a tuple when Field class created.

答案有点深。“错误”是创建 Field 类时的元组。

class Field(object):
    """
    Field base class
    """
    errors = tuple()

But when method validate called, it convert it to list

但是当调用方法验证时,它将其转换为列表

def validate(self, form, extra_validators=tuple()):
    self.errors = list(self.process_errors)

So everything you need is just to call your email_unique function right after validate_on_submit, which in turns call validate function of the form and convert errors to list

所以你需要的只是在validate_on_submit之后立即调用你的email_unique函数,它依次调用表单的validate函数并将错误转换为列表

@app.route('/register', methods = ['GET', 'POST'])
def register():
    form = RegisterForm()
    #makes the username unique
    u_unique =  form.username.data
    u_unique = User.unique_username(u_unique)

    #validates email adress and checks if it already exists or 

    if form.validate_on_submit():
        form.email_unique(form.email.data)
        user = User(
            u_unique,
            form.password.data, 
            form.email.data, 
            form.age.data, 
            form.about_user.data,
            form.img_url.data)
        db.session.add(user)
        db.session.commit()
        flash('Thank you for your registration')
        flash('Your username is: ' + str(u_unique))
        return redirect(url_for('login'))
    else:
        for error in form.errors:
            flash(error)

    return render_template('register.html',
        title = 'Registeration',
        form = form)