Update Flask User Information

Asked 1 years ago, Updated 1 years ago, 489 views

We are creating a page to update user information.
After pressing the "Change" button of the user in user_maintenance.html, it transitions to account.html.
For some reason, the user name shows the user name from which it was updated, but the email address part does not appear (see figure).

I just don't know what's wrong.

I would appreciate it if you could let me know.
Enter a description of the image here

app.py

 class User (db.Model):
    __tablename__='users'
 
    id=db.Column(db.Integer, primary_key=True)
    email=db.Column(db.String(64), unique=True, index=True)
    username=db.Column (db.String(64), unique=True, index=True)
    password_hash = db.Column(db.String(128))
    administrator=db.Column(db.String(1))
    post=db.relationship('BlogPost', backref='author', lazy='dynamic')
 

    def__init__(self, email, username, password_hash, administrator):
        self.email=email
        self.username=username
        self.password_hash=password_hash
        self.administrator=administrator


    def__repr__(self):
        returnf "UserName: {self.username}"


class RegistrationForm (FlaskForm):
    # Create each field to display in HTML
    email=StringField('email address', validators=[DataRequired(), Email(message='Please enter a valid email address')])
    username=StringField('username', validators=[DataRequired()])
    password=PasswordField('password', validators=[DataRequired(), EqualTo('pass_confirm', message='Please enter a valid password')])
    pass_confirm=PasswordField('password (confirmation), validators=[DataRequired()])
    submit=SubmitField('Register')

    default_username(self,field):
        if User.query.filter_by(username=field.data).first():
            raise ValidationError('User is already in use.')

    default_email(self,field):
        if User.query.filter_by (email=field.data).first():
            raise ValidationError('email address is already in use.')


class UpdateUserFome (FlashForm):
    email=StringField('email address', validators=[DataRequired(), Email(message='Please enter a valid email address')])
    username=StringField('username', validators=[DataRequired()])
    password=PasswordField('password', validators=[DataRequired(), EqualTo('pass_confirm', message='passwords do not match')])
    pass_confirm=PasswordField('password (confirmation), validators=[DataRequired()])
    submit=SubmitField('Update')

    def_init__(self, user_id, *args, **kwargs):
        # to be able to perform the necessary processing while leaving the class from which to inherit
        super(UpdateUserFome,self).__init__(*args,**kwargs)
        self.id=user_id

@app.route('/<int:user_id>/account', methods=['GET', 'POST'])
def account(user_id):
    user=User.query.get_or_404(user_id)
    form = UpdateUserFome(user_id)
    # update processing
    if form.validate_on_submit():
        # Store data obtained in the form with elif in the model
        user.username=form.username.data
        user.email=form.email.data
        # The password is updated only when it is filled in the form, so check if it is filled in the form.
        if form.password.data:
            user.password_hash=form.password.data
        db.session.commit()
        flash('Updated')
        return redirect(url_for('user_maintenance'))
    # initial display
    elif request.method=='GET':
        # User name and mail retrieved from DB are stored in the form
        form.username.data=user.username
        form.email.date=user.email 
    return render_template ('account.html', form=form)

if__name__=='__main__':
    app.run(debug=True)

user_maintenance.html

<div class="card-header">
    <h4> Latest Users</h4>
</div>
<table class="table table-striped">
    <thead class="table-dark">
        <tr>
            <th>ID</th>
            <th> Username </th>
            <th>Email address</th>
            <th>Administrator</th>
            <th>Number of blog posts</th>
            <th>Change</th>
        </tr>
    </thead>
    <tbody>
        {% for user in users%}
        <tr>
            <td>{{user.id}}</td>
            <td>{{user.username}}</td>
            <td>{{user.email}}</td>
            <td>{{user.administrator}}</td>
            <td><a href="#">Number of blog posts</a></td>
            <td><a href="{url_for('account', user_id=user.id)}}" class="btn btn-secondary">
                change
            </a></td>
        </tr>
        {% endfor%}
    </tbody>  
</table>

account.html

<h3>User Updates</h3>
<p>Change user information.</p>
<form method="POST">
    {{ form.hidden_tag()}}
    <div class="mb-3">
        {{ render_field(form.username, placeholder="username", class="form-control form-control-lg")}}
    </div>
    <div class="mb-3">
        {{ render_field(form.email, placeholder="mail address", class="form-control form-control-lg")}}
    </div>
    <div class="mb-3">
        {{ render_field(form.password,placeholder="new password",class="form-control form-control-lg")}}
    </div>
    <div class="mb-3">
        {{ render_field(form.pass_confirm,placeholder="new password (confirmation),class="form-control form-control-lg")}}
    </div> 
    {{ form.submit(class="btn btn-outline-light w-100", value="Update")}} 
</form>

python html flash

2023-02-25 21:46

1 Answers

As far as I can read the source, I think the passing of the form to the field is data, but only one part is date.

@app.route('/<int:user_id>/account', methods=['GET', 'POST'])
def account(user_id):
    ## (omitted)
    # initial display
    elif request.method=='GET':
        # User name and mail retrieved from DB are stored in the form
        form.username.data=user.username
        substituting form.email.date=user.email#<-'date'
    return render_template ('account.html', form=form)


2023-02-25 23:31

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.