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.
除了以上字段外,管理员在表单中还能编辑用户的电子邮件、用户名、确认状态和角色,表单定义如下:
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.')
app/main/views.py:管理员的资料编辑路由
@main.route('/edit-profile/', methods=['GET', 'POST'])
@login_required
@admin_required
def edit_profile_admin(id):
user = User.query.get_or_404(id)
form = EditProfileAdminForm(user)
if form.validate_on_submit():
user.email = form.email.data
user.username = form.username.data
user.confirmed = form.confirmed.data
user.role = form.role.data
user.name = form.name.data
user.about_me = form.about_me.data
user.location = form.location.data
db.session.add(user)
db.session.commit()
flash("The profile has been updated.")
return redirect(url_for(".user", username=user.username))
form.email.data = user.email
form.username.data = user.username
form.confirmed.data = user.confirmed
form.role.data = user.role
form.name.data = user.name
form.about_me.data = user.about_me
form.location.data = user.location
return render_template("edit_profile.html", form=form, user=user)
分析: