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?

webアプリ my-favorite-list 一覧機能

Posted at

一覧

したこと:ページネーションと詳細

流れ

views.py -> urls.py -> anime_list.html
フォームの基礎 -> 選択肢 -> 見た目 -> urlの設定 -> html(ユーザーの見た目)

役割

views.py(データをhtmlに渡すため)/ urls.py(urlの設定)/html(ユーザーに見せる)

ポイント:urlの指定

ページネーションではint:pkを使わない理由 = 一意ではないため。(その特定の情報)
例えば:アニメの「君の名は。」は一意
アニメのページネーションでの2/80ページ目は特定できない

ページネーションとは:データを複数のページに分割する
例えば:アニメのデータが1189件あった場合、15 * 80 ページにする

views.py

  • dbからアニメのデータを全て取得
  • paginatorクラスでデータを分割
  • ユーザーのリクエストが渡してきたパラメータを取得(ページの取得)
  • パラメータからページのデータのみを取得(urlを簡単にする) -> データをhtmlに渡す
def anime_list(request):
	anime_queryset = Anime.objects.all()
	paginator = Paginator(anime_queryset, 15)
	page_number = request.GET.get('page')
	page_obj = paginator.get_page(page_number)
	return render(request, 'myapp/anime_list.html', {'page_obj' : page_obj})

urls.py

  • urlは指定しなくても変わる(ページネーションとか、その特定のデータではない場合)

path('anime/', views.anime_list, name='anime_list'),

html

  • ul内でデータの受け渡し
  • ページネーションで前後ページの有り無しで場合分け
  • urlでボタンを作る(homeボタン等)
<!DOCTYPE html>
<html>
<head>
    {% load static %}
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>anime_list</title>
    <link rel="stylesheet" href="{% static 'myapp/css/anime_list.css' %}"> <!-- 修正済み -->
</head>
<body>
    <h1>アニメ一覧</h1>
    <ul>
        {% for anime in page_obj.object_list %}
            <li>
                <a href="{% url 'anime_detail' anime.id %}">{{ anime.title }}</a>
            </li>
        {% endfor %}
    </ul>

    <!-- ページネーションのリンク -->
    <div class="pagination">
        {% if page_obj.has_previous %}
            <a href="?page=1">最初</a>
            <a href="?page={{ page_obj.previous_page_number }}">前へ</a>
        {% endif %}

        <span>ページ {{ page_obj.number }} / {{ page_obj.paginator.num_pages }}</span>

        {% if page_obj.has_next %}
            <a href="?page={{ page_obj.next_page_number }}">次へ</a>
            <a href="?page={{ page_obj.paginator.num_pages }}">最後</a>
        {% endif %}
    </div>

    <!-- リンクボタン-->
    <div class = "group">
        <a href="{% url  'anime_form' %}" class = "button">追加</a>
        <a href="{% url  'anime_search' %}" class = "button">検索</a>
        <a href="{% url  'home' %}" class = "button">Home</a>
    </div>
</body>
</html>
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?