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

Deadly 提交于 2019-12-04 10:44:38
A.J. Uppal

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

>>> 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!

tuples are 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:

>>> 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]

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.

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

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

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

@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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!