flask網頁建設主題三

個人頁面上的顯示推文,只顯示自己的貼文

Steven Wang
6 min readNov 27, 2020

新增post
t1=Tweet(body=’my name is admin’,user_id=1)
db.session.add(t1)
db.session.commit()

relationship /backref=’author’ 應用取得特定User的post

Tweet.query.filter_by(user_id=1).all()
這樣需要知道user_id不一定方便使用
用user / current_user 去獲取user_id 會比較方便
技術上user可行是因為有做好下面紅框這個

tweets = db.relationship('Tweet', backref = 'author' ,lazy = 'dynamic')

為了可以用user做以上的filter
我們在class User作了關聯relationship並且backref=’author’
author是User的物件

(1)id=1
u_admin = User.query.filter_by(id=1).first()
u_admin

(2)author=user
Tweet.query.filter_by(author=u_admin).all()

(1)(2)結果一樣

但是好處是
Tweet.query.filter_by(author=u_admin).all()
使用物件去查詢替代id方便很多
取得特定用戶的所有推post

也可以透過t1.author去訪問 「發表這貼文的人」的物件

dir(t1)屬性很多,包含author
t1是Tweet物件,透過author直接獲取發表貼文t1的User物件
否則要透過t1的user_id取得User.query.filter_by(id=user_id).first()會麻煩多了

將新的提取資料方式放入route.py

修改接收資料的 user.html

如果知道User物件也可以直接知道他的貼文

u1.tweets.all()

修改router.py / u.tweets

登入主頁面顯示的推文,顯示除了自己的貼文外, 自己關注的貼文也要顯示

own = Tweet.query.filter_by(user_id=self.id)找出自己的推文
followed = Tweet.query.join(followers,(followers.c.followed_id== Tweet.user_id)).filter(followers.c.follower_id==self.id)找出自己關注的推文
return followed.union(own).order_by(Tweet.create_time.desc())

Tweet.query.join(followers 將Tweet與follwes這兩張表join成followed表,join的條件是(followers.c.followed_id== Tweet.user_id)
這樣會全部進入
但是我們只關心我們關注的推文
因此filter(followers.c.follower_id==self.id)
這樣結果就是我所關注的貼文
union兩張表followed/own,並做desc降序的排序order_by

修改router.py

tweets = current_user.own_and_followed_tweets()

修改接收資料的 index.html

子模板SubTemplate

網頁一樣的部分拿出來做成子模板
/templates/_tweets.html

user.html/{% include “_tweets.html”%}

index.html/{% include “_tweets.html”%}

子板模修改,user.html / index.html 就會跟著變

發表post的功能製作

(1)發表需要有地方輸入
首先需要一個form / from.py
class TweetForm(FlaskForm):
about_me = TextAreaField(‘Tweet’, validators=[DataRequired(), Length(min=0, max=140)])
submit = SubmitField(‘Tweet’)

(2)index.html用這個form,需要init.py改url / & url/index 成能接收post

(3)修改route.py
if form.validate_on_submit(): 如果是post方式

如果不是post方式
form=form 將form傳遞到template/index.html裡面(目前index.html還沒有form的使用)

(4)修改templates/index.html

成果

--

--

Steven Wang
Steven Wang

No responses yet