When submitting a Flask WTForms, how can fields be left blank without blanking-out those values from the database table?

Michael Scott Perkins

Question:

I'm working on a Flask app w/ a WTForms EditProfileForm containing: First Name, Last Name, Username, and About Me. The form loads w/ Username and About Me auto-populated. First Name and Last Name are blank. If the user edits the About Me TextAreaField, but leaves the First Name and Last Name fields blank, submitting the form overwrites those DB fields as blank.

Related Code Examples:

  • In the following forms.py code example, I had validators=[DataRequired()]) on firstname and lastname, but since those fields were showing up blank, it was requiring the user to re-enter their first and last name any time they wanted to edit any field(s). So I removed those validator.

  • Also on first and last name there is a username validate function so that if the user does not change their Username, which must be unique, upon submission the query doesn't return the false-positive error that the username must be unique.

forms.py - EditProfileForm class:

class EditProfileForm(FlaskForm):
    firstname = StringField('First Name')
    lastname = StringField('Last Name')
    username = StringField('Username', validators=[DataRequired()])
    about_me = TextAreaField('About Me', validators=[Length(min=0, max=140)])
    submit = SubmitField('Submit')

    def __init__(self, original_username, *args, **kwargs):
        super(EditProfileForm, self).__init__(*args, **kwargs)
        self.original_username = original_username

    def validate_username(self, username):
        if username.data != self.original_username:
            user = User.query.filter_by(username=self.username.data).first()
            if user is not None:
                raise ValidationError('Please choose a different username.')
  • I can't find anything in the View function that is causing the firstname and lastname fields to appear blank but the username and about_me fields to auto-populate.

routes.py - the edit_profile view

@app.route('/edit_profile', methods=['GET', 'POST'])
@login_required
def edit_profile():
    form = EditProfileForm(current_user.username)
    if form.validate_on_submit():
        current_user.firstname = form.firstname.data
        current_user.lastname = form.lastname.data
        current_user.username = form.username.data
        current_user.about_me = form.about_me.data
        db.session.commit()
        flash(_('Your changes have been saved.'))
        return redirect(url_for('edit_profile'))
    elif request.method == 'GET':
        form.username.data = current_user.firstname
        form.username.data = current_user.lastname
        form.username.data = current_user.username
        form.about_me.data = current_user.about_me
    return render_template('edit_profile.html', title=_('Edit Profile'),
                           form=form)

models.py - the User class

class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    firstname = db.Column(db.String(50), index=True)
    lastname = db.Column(db.String(50), index=True)
    username = db.Column(db.String(50), index=True, unique=True)
    email = db.Column(db.String(120), index=True, unique=True)
    password_hash = db.Column(db.String(128))
    about_me = db.Column(db.String(140))

    def __repr__(self):
        return '<User {}>'.format(self.username)

    def set_password(self, password):
        self.password_hash = generate_password_hash(password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

edit_profile.html

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

    {% block app_content %}
        <h1>Edit Profile</h1>
        <div class="row">
            <div class="col-md-4">
                {{ wtf.quick_form(form) }}
            </div>
        </div>
    {% endblock %}
Michael Scott Perkins

Turns out, the problem was a simple copy/paste error that I made in the routes.py edit_profile view function. I had this...

    form.username.data = current_user.firstname
    form.username.data = current_user.lastname
    form.username.data = current_user.username
    form.about_me.data = current_user.about_me

I had form.username.data in three out of the four field. Doh!

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

Pass Form Values to Update Query without updating blank fields in table

分類Dev

how to get SUM of a set of values from a table then the MAX of those values and echo the 5 highest values

分類Dev

How to transpose values from certain columns in google form, [ignore those with blank values] into part of email htmlBody using GAS?

分類Dev

How can I load dates from database table to fullcalender using PHP code? [without ajax]

分類Dev

undefined index error when submitting form and inserting values into database?

分類Dev

How can I save only those rows from a DataFrame which columns have values from the list?

分類Dev

How to select all non blank cells and paste in table without overriding existing values

分類Dev

How can I SUM values in a joined table without screwing up totals of values in the first table?

分類Dev

enabling blank values into database

分類Dev

how to view the data when searching without submitting | angularjs

分類Dev

Flask WTForms - Custom validators based of multiple form fields

分類Dev

How to left join when there are repeating left table observations?

分類Dev

Flask initialize database with values

分類Dev

How to set specific data from database in fields when launch through activity shortcut?

分類Dev

How to recreate database in SQLAlchemy from Flask?

分類Dev

how to disable monitor sleep/blanking?

分類Dev

How can I add and get all my database table values (numbers) and displaying the total amount? C#

分類Dev

How to update records when many fields in Flask. Python

分類Dev

Getting all unique values and the count of their occurences from Flask SQLAlchemy table

分類Dev

How to update a database table letting two fields be empty/not filled/null

分類Dev

how to populate a table's fields with multiple values depending on the row

分類Dev

Taking ids from two rows of one MySQL table and entering those values in one row of another MySQL table using PHP

分類Dev

How can I drop database in hive without deleting database directory?

分類Dev

Redshift - Filter out rows that are blank to left or right of a character

分類Dev

how to populate database fields when model changes in django

分類Dev

Retrieving values from fields

分類Dev

How to refresh a page without form submitting?

分類Dev

Flask WTForms FieldList with BooleanField

分類Dev

How to populate jtable checkbox values from database?

Related 関連記事

  1. 1

    Pass Form Values to Update Query without updating blank fields in table

  2. 2

    how to get SUM of a set of values from a table then the MAX of those values and echo the 5 highest values

  3. 3

    How to transpose values from certain columns in google form, [ignore those with blank values] into part of email htmlBody using GAS?

  4. 4

    How can I load dates from database table to fullcalender using PHP code? [without ajax]

  5. 5

    undefined index error when submitting form and inserting values into database?

  6. 6

    How can I save only those rows from a DataFrame which columns have values from the list?

  7. 7

    How to select all non blank cells and paste in table without overriding existing values

  8. 8

    How can I SUM values in a joined table without screwing up totals of values in the first table?

  9. 9

    enabling blank values into database

  10. 10

    how to view the data when searching without submitting | angularjs

  11. 11

    Flask WTForms - Custom validators based of multiple form fields

  12. 12

    How to left join when there are repeating left table observations?

  13. 13

    Flask initialize database with values

  14. 14

    How to set specific data from database in fields when launch through activity shortcut?

  15. 15

    How to recreate database in SQLAlchemy from Flask?

  16. 16

    how to disable monitor sleep/blanking?

  17. 17

    How can I add and get all my database table values (numbers) and displaying the total amount? C#

  18. 18

    How to update records when many fields in Flask. Python

  19. 19

    Getting all unique values and the count of their occurences from Flask SQLAlchemy table

  20. 20

    How to update a database table letting two fields be empty/not filled/null

  21. 21

    how to populate a table's fields with multiple values depending on the row

  22. 22

    Taking ids from two rows of one MySQL table and entering those values in one row of another MySQL table using PHP

  23. 23

    How can I drop database in hive without deleting database directory?

  24. 24

    Redshift - Filter out rows that are blank to left or right of a character

  25. 25

    how to populate database fields when model changes in django

  26. 26

    Retrieving values from fields

  27. 27

    How to refresh a page without form submitting?

  28. 28

    Flask WTForms FieldList with BooleanField

  29. 29

    How to populate jtable checkbox values from database?

ホットタグ

アーカイブ