LoginSignup
1
0

More than 1 year has passed since last update.

Django初心者がSNSアプリを作る その2

Last updated at Posted at 2022-08-17

前回 https://qiita.com/YuDachi/items/2c46930fe33c4c7e70bb
元記事 https://note.com/saito_pythonista/n/n6550f5c2a07b

今回から、元記事の「4.2 CRUD機能」を、ユーザー関連の機能を除いて実装する。

投稿一覧ページの実装

元記事の「4.2.1 ①投稿記事の"一覧"ページ表示機能」に相当する部分を実装する。

Templateの作成

前回も書いたが、効率性を無視してとことんわかりやすいところから実装する。まずはページの表示"のみ"を目標にしよう。

templates下にlist.htmlを作成し表示したいのだが、今後の便宜のためにちょっとした準備をする。HTMLに関する共通しそうな設定はすべてbase.htmlに書き、それをextendsで個々のHTMLファイルに引っ張るという形式を採用する。こうすることで同じ設定を何度も書かずに済む。

templates/base.html

templates/base.html
{% load static %}

<!doctype html>
<html lang="ja">

<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">

<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.1/css/all.css" integrity="sha384-vp86vTRFVJgpjF9jiIGPEEqYqlDwgyBgEF109VFjmqGmIY/Y4HV4d3Gp2irVfcrp" crossorigin="anonymous">
    
{% block customcss %}
{% endblock customcss %}

<title>SNSアプリサンプル</title>

</head>

<body>

{% block content %}
{% endblock content %}

</body>

</html>

これで customcss, content 以外の部分を共通化できる。次にlist.htmlを作成し、base.htmlの内容をextendsで持ってくる。表示させることが目標なので中身は適当。

templates/list.html

templates/list.html
{% extends 'base.html' %}
{% load static %}

{% block content %}

    <h1>THIS IS LIST</h1>

{% endblock content %}

このあたりの実装も書籍「現場で使える Django の教科書《基礎編》」に書いてあった。

viewとURLの設定

作ったテンプレートを表示するためviewとURLを設定する。
元記事ではListViewを用いているが、modelがないとエラーで動かないっぽいので、代わりにTemplateViewを使った。冗長だと思う人はmodelを作成して最初からListViewを使えばいいと思う。

snsapp/views.py

snsapp/views.py
from django.http import HttpResponse
from django.views.generic import TemplateView # 追加

...

# 追加
class Home(TemplateView):
    template_name = "list.html"

snsapp/urls.py

snsapp/urls.py
from django.urls import path

from .views import Home # 追加

urlpatterns = [
    path('', Home.as_view(), name='home'), # 訂正
]

これで"ページの表示"という目標が達成できた。

次回はlist.htmlをもう少しいじって、投稿一覧ページのイメージを作成する。

1
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
1
0