1.主PY文件寫視圖函數,帶id參數。 html
@app.route('/detail/<question_id>')
def detail(question_id):
quest =
return render_template('detail.html', ques = quest)app
@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.首頁標題的標籤作帶參數的連接。
{{ url_for('detail',question_id = foo.id) }}函數
{% block main%} <p>{{user}} context</p> <ul class="list-group"> {% for foo in questions %} <li class="list-group-item"> <span class="glyphicon glyphicon-leaf" aria-hidden="true"></span> <a href="#">{{ foo.author.username }}</a> <br> <a href="{{ url_for('detail',question_id=foo.id) }}">{{ foo.title }}</a> <span class="badge">{{ foo.creat_time }}</span> <p style="color:black">{{ foo.detail }}</p> </li> {% endfor %} </ul> {% endblock %}
3.在詳情頁將數據的顯示在恰當的位置。 post
{{ ques.title}}
{{ ques.id }}{{ ques.creat_time }}
{{ ques.author.username }}
{{ ques.detail }}
{% extends 'base.html' %} {% block title %}問答詳情{% endblock %} {% block main %} <div class="page-header"> <h3>題目:{{ ques.title }}<br><small>做者:{{ ques.author }} 發佈時間:{{ ques.create_time }}</small></h3> </div> <p class="lead">detail{{ ques.detail }}</p> <hr> <form action="{{ url_for('question') }}" method="post"> <div class="form-group"> <textarea name="new_comment" class="form-control" rows="3" id="new_comment" placeholder="write your comment"></textarea> </div> <button type="submit" class="btn btn-default">發送</button> </form> <ul class="list-group" style="margin: 10px"></ul> {% endblock %}
4.創建評論的對象關係映射:url
class Comment(db.Model):
__tablename__='comment'spa
5. 嘗試實現發佈評論。 code
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')) creat_time = db.Column(db.DateTime,default=datetime.now) detail = db.Column(db.Text,nullable=False) question = db.relationship('Question',backref = db.backref('comments')) author = db.relationship('User',backref = db.backref('comments'))