从首页问答标题到问答详情页
2017-12-06 21:47 055李小锐 阅读(187) 评论(0) 编辑 收藏 举报
- 主PY文件写视图函数,带id参数。
@app.route('/detail/<question_id>')
def detail(question_id):
quest =
return render_template('detail.html', ques = quest) - 首页标题的标签做带参数的链接。
{{ url_for('detail',question_id = foo.id) }} - 在详情页将数据的显示在恰当的位置。
{{ ques.title}}
{{ ques.id }}{{ ques.creat_time }}{{ ques.author.username }}
{{ ques.detail }} -
建立评论的对象关系映射:
class Comment(db.Model):
__tablename__='comment' -
尝试实现发布评论。
1.
@app.route('/detail/<question_id>') def detail(question_id): quest=Question.query.filter(Question.id==question_id).first() return render_template('detail.html',ques=quest)
2.
<a href="{{url_for('detail',question_id=foo.id)}}">{{ foo.title }}</a>
3.
<li class="list-group-item"> <h3>{{ ques.title }}<br><small>{{ ques.author.username }}<span class="badge">{{ ques.creat_time }}</span> </small></h3> </li>
4.
class Comment(db.Model): __tablename__ ='comment' id=db.Column(db.Integer,primary_key=True,autoincrement=True) author_id=db.Column(db.Integer,db.ForeignKey('user.id')) question_id=db.Column(db.Integer,db.ForeignKey('question.id')) detail=db.Column(db.DateTime,default=datetime.now) question=db.relationship('Question',backref=db.backref('comments',order_by=creat_time.desc)) author=db.relationship('User',backref=db.backref('comments'))
5.
@app.route('/comment/',methods=['POST'])
@login_re
def comment():
if request.method == 'GET':
return render_template('detail.html')
else:
detail = request.form.get('detail')
question_id = User.query.filter(User.username == session.get('user')).first().id
comment = Comment( detail=detail, question_id=question_id)
db.session.add(comment)
db.session.commit()
return redirect(url_for('index'))
def login_re(func):
@wraps(func)
def wrapper(*args, **kwargs):
if session.get('comment'):
return func(*args,**kwargs)
else:
return redirect(url_for('login'))
return wrapper