Flask Web 开发 用户资料_2

49 篇文章 2 订阅
41 篇文章 3 订阅

继续上一篇章

有了用户资料的页面,那总归要可以编辑吧,那编辑就涉及到通过表单来提交

所以,我们又要来新建一个Form了

main/forms.py

from flask.ext.wtf import Form
from wtforms import StringField,SubmitField,TextAreaField
from wtforms.validators import Required,Length

	
class EditProfileForm(Form):
	name = StringField('Real name',validators=[Length(0,64)])        #这里Length设置(0,64)的意思是可选项,不一定必填
	location = StringField('Location',validators=[Length(0,64)])
	about_me = TextAreaField('About me')                             #TextAreaField,一个文本框功能
	submit = SubmitField('Submit')


表单建立好了,那就接着建立 路由功能


@main.route('/edit-profile',methods=['GET','POST'])
@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)
		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     #显示的内容是预设值,而预设值就是在提交之前,current_user的各项属性值
	form.about_me.data = current_user.about_me
	return render_template('edit_profile.html',form = form)


在显示表单之前,这个视图函数为所有字段设定了初始值。对于所有给定字段,这一工作都是通过把初始值赋值给form.<field-name>.data 完成的。当form.validate_on_submit()返回False 时,表单中的3 个字段都使用current_user 中保存的初始值。提交表单后,表单字段的data 属性中保存有更新后的值,因此可以将其赋值给用户对象中的各字段,然后再把用户对象添加到数据库会话中

然后,作者在制作Edit Profile按钮的时候,设置了一个条件语句,这样做的目的是,只有当用户是你自己时候,才能生成这个链接

app/templates/user.html

{% if user == current_user %}
<a class="btn btn-default" href="{{ url_for('.edit_profile') }}">
Edit Profile
</a>
{% endif %}



点击以后,就可以修改你的个人资料了

由于国内google被墙,所以地图的对应我改成百度的了





修改完以后,就可以看到下面的效果图了,我红线标注的地方是将地图导航改成百度的地图.





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值