第十章 用户资料(二)

一. 用户级资料编辑器

app/main/forms.py:资料编辑表单

class EditProfileForm(FlaskForm):
    name = StringField('Real name', validators=[Length(0, 64)])
    location = StringField('Location', validators=[Length(0, 64)])
    about_me = TextAreaField('About me')
    submit = SubmitField('Submit')

注意:这个表单中的所有字段都是可选的,因此长度验证的最小值为0.

app/main/views.py:资料编辑路由

@main.route('/edit-profile', methods=['POST', 'GET'])
@login_required
def edit_profile():
    form = EditProfileForm()
    if form.validate_on_submit():
        current_user.name = form.name.data
        current_user.location = form.location.data
        current_user.about_me = form.about_me.data
        db.session.add(current_user._get_current_object())
        db.session.commit()
        flash('Your profile has been updated.')
        return redirect(url_for('.user', username=current_user.username))
    form.name.data = current_user.name
    form.location.data = current_user.location
    form.about_me.data = current_user.about_me
    return render_template('edit_profile.html', form=form)

字段中的数据使用form..data获取,通过这个表达式不仅能获取用户提交的值,还能在字段中显示初始值,供用户编辑。当form.validate_on_submit()返回False时,表单中的3个字段都使用current_user中保存的初始值,提交表单后,表单字段的data属性中保存有更新后的值。用户级资料编辑界面如下:

第十章 用户资料(二)_第1张图片

二. 管理员级资料编辑器

除了以上字段外,管理员在表单中还能编辑用户的电子邮件、用户名、确认状态和角色,表单定义如下:

class EditProfileAdminForm(FlaskForm):
    email = StringField('Email', validators=[DataRequired(), Length(1, 64), Email()])
    username = StringField('Username', validators=[
        DataRequired(), Length(1, 64),
        Regexp("^[a-zA-Z][a-zA-Z0-9_.]*$", 0, 'Usernames must have only letters, numbers, dots or underscores')])
    confirmed = BooleanField('Confirmed')
    role = SelectField('Role', coerce=int)
    name = StringField('Real name', validators=[Length(0, 64)])
    location = StringField('Location', validators=[Length(0, 64)])
    about_me = TextAreaField('About me')
    submit = SubmitField('Submit')

    def __init__(self, user, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.role.choices = [(role.id, role.name) for role in Role.query.order_by(Role.name).all()]
        self.user = user

    def validate_email(self, field):
        if field.data != self.user.email and User.query.filter_by(email=field.data).first():
            raise ValidationError('Email already registered.')

    def validate_username(self, field):
        if field.data != self.user.username and User.query.filter_by(username=field.data).first():
            raise ValidationError('Username already in use.')
  • SelectField是WTForms对HTML表单控件