Google App Engineで開発をしています。
言語はPythonで、テンプレートエンジンはjinja2です。
質問サイトを作りたいのですが、teratailと同様、各質問に対してタグがつくようにしたいと考えています。
質問文とタグを一つ選択し投稿すると、質問とタグが紐付いた形でデータベースに登録され、質問一覧に質問の内容とそのタグが表示されるというものです。
下記のとおり、QuestionsとTagsの各モデルを定義しています。
python
1class Questions(ndb.Model): 2content = ndb.TextProperty(indexed = False) 3tag = ndb.IntegerProperty(indexed = False) 4 5class Tags(ndb.Model): 6id = ndb.IntegerProperty(indexed=True) 7name = ndb.StringProperty(indexed=False)
Tagsには、
1:英語、2:フランス語、3:中国語、...といった感じで、idとnameが既に登録されています。
質問の投稿画面は、下記のとおりです。
python
1class MainPage(webapp2.RequestHandler): 2 def get(self): 3 template_values = { 4 'tags': tags, 5 } 6 template = JINJA_ENVIRONMENT.get_template('index.html') 7 self.response.write(template.render(template_values)) 8class Question(webapp2.RequestHandler): 9 def post(self): 10 question = Questions() 11 question.tag = int(self.request.get('tag')) 12 question.content = self.request.get('content') 13 question.put() 14app = webapp2.WSGIApplication([ 15 ('/', MainPage), 16 ('/sign',Question), 17], debug = True)
html
1/*index.html*/ 2<form method="post" action="/sign"> 3 <select name="tag"> 4 {% for tag in tags %} 5 <option value={{tag.id}}>{{tag.name}}</option> 6 {% endfor %} 7 </select> 8 <textarea cols=100% name="content" rows="13" placeholder="分 9 からないこと、解決したいことの詳細を書いてください"></textarea> 10 <button class"btn btn-default" type="submit">submit</button> 11</form>
タグを一つ選択し、質問文を書いて、submitします。
ここまではうまくいっています(質問データは、登録されています。)。
これを受けて、質問一覧を表示する画面は、下記のとおりに書いています。
python
1class MainPage(webapp2.RequestHandler): 2 def get(self): 3 question_query = Questions.query() 4 questions = question_query.fetch(10) 5 template_values = { 6 'questions': questions, 7 } 8 template = JINJA_ENVIRONMENT.get_template('index.html') 9 self.response.write(template.render(template_values))
html
1/*index.html*/ 2{% for question in questions %} 3 {{question.content}} 4 {{question.tag}} 5{% endfor %}
これにより、質問とタグのidが表示されるところまではいきました。
しかし、タグのidではなく、タグ名を表示するにはどうしたらよいでしょうか?
現在は、例えば、idの「1」が表示されていますが、そうではなく、nameの「英語」が表示されて欲しいということです。
どういう仕組みを使えばこれが可能なのか、思いつきません。
お分かりの方、ご教示頂ければ幸いです。
よろしくお願いいたします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。