0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Djangoの学習④(ビューとテンプレートの追加)

0
Posted at

ビューを追加する

ビューは、Django のアプリケーションにおいて特定の機能を提供する
ウェブページの「型 (type)」であり、各々のテンプレートを持っています。

追加するviewを polls/views.py に記述します

polls/views.py
def detail(request, question_id):
    return HttpResponse("You're looking at question %s." % question_id)

def results(request, question_id):
    response = "You're looking at the results of question %s."
    return HttpResponse(response % question_id)

def vote(request, question_id):
    return HttpResponse("You're voting on question %s." % question_id)

追加した新しいviewを polls.urls モジュールと結びつけます。

polls/urls.py
urlpatterns = [
    # ex: /polls/
    path("", views.index, name="index"),
    # ex: /polls/5/
    path("<int:question_id>/", views.detail, name="detail"),
    # ex: /polls/5/results/
    path("<int:question_id>/results/", views.results, name="results"),
    # ex: /polls/5/vote/
    path("<int:question_id>/vote/", views.vote, name="vote"),
]

試しに
http://127.0.0.1/:8000/polls/34/
にアクセスしてみてみます

「You're looking at question 34.」
と表示されれば成功です

以下、2つも確認します
http://127.0.0.1/:8000/polls/34/results/
「You're looking at the results of question 34.」
http://127.0.0.1/:8000/polls/34/vote/
「You're voting on question 34.」

実際に動作するビューを書く

各ビューには二つの役割があります:
一つはリクエストされたページのコンテンツを含む HttpResponse オブジェクトを返すこと、
もう一つは Http404 のような例外の送出です。

polls/indexビューは既にありますが
味気ないテキストを表示するだけの状態なので
ビューに下記を追記し更新します

polls/views.py
from django.template import loader
from .models import Question
# Create your views here.
def index(request):
    latest_question_list = Question.objects.order_by("-pub_date")[:5]
    template = loader.get_template("polls/index.html")
    context = {
        "latest_question_list": latest_question_list,
    }
    return HttpResponse(template.render(context, request))

次にビューのテンプレートを作成します。
polls ディレクトリの中に、
templates ディレクトリを作成します。 Django はそこからテンプレートを探します。

先ほど作成した templates ディレクトリ内で polls というディレクトリを作成し、
さらにその中に index.html というファイルを作成します。
つまり、テンプレートは polls/templates/polls/index.html に書く必要があります。

polls/templates/polls/index.html

{% if latest_question_list %}
    <ul>
    {% for question in latest_question_list %}
        <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p>No polls are available.</p>
{% endif %}

ブラウザで "/polls/" を開くと、作成したQuestionの箇条書きのリストが表示されるはずです。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?