Re:ゼロから始める文系プログラマ

未経験がプログラミングを通して人生を変える

【Django】簡単なSNSアプリを開発する⑤~ListViewの表示~


スポンサードリンク
 

f:id:ShotaNukumizu_1000:20211205071412p:plain

おはようございます。Shotaです。

今回の記事では、DjangoでListViewを表示するための方法を詳細に解説していきます。

▼前回の記事はコチラ

shotanukumizu-1000.hatenablog.com

▼初回の記事はコチラ

shotanukumizu-1000.hatenablog.com



投稿内容の表示(ListView)

_app/views.pyに以下のコードを書いてください。

#_app/views.py
from .models import ArticleModel

from django.db import IntegrityError
from django.shortcuts import render, redirect

from django.contrib.auth import authenticate, login, logout

from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required #忘れないように!


def signupfunc(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        try:
            user = User.objects.create_user(username, '', password)
            return render(request, 'login.html', {})
        except IntegrityError:
            return render(request, 'signup.html', {'error': 'このユーザはすでに登録されています'})
    return render(request, 'signup.html', {})


def loginfunc(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(request, username=username, password=password)

        if user is not None:
            login(request, user)
            return redirect('index')
        
        else:
            return render(request, 'login.html', {})
    
    return render(request, 'login.html', {})

#編集
@login_required
def index_func(request):
    object_list = ArticleModel.objects.all()
    return render(request, 'index.html', {'object_list': object_list})

def logoutfunc(request):
    logout(request)
    return redirect('login')

▼追加するコード

@login_required
def index_func(request):
    object_list = ArticleModel.objects.all()
    return render(request, 'index.html', {'object_list': object_list})

こちらのコードを書いて、templates/index.htmlに投稿内容の一覧を表示させるようにします。関数renderの第三引数にobject_listを設定して、そこに作成したモデルを表示させていきます。

あと、この「投稿内容を表示させる」という機能はログインしている状態にのみ機能させるようにしたいので、関数の前に@login_requiredを付けてDjango側にそのように処理させるようにします。(いわゆる「アノテーション」)

あとはtemplates/index.htmlに以下のコードを書くだけです。

{% extends 'base.html' %}

{% block title %}
<title>投稿内容</title>
{% endblock title %}

{% block header %}
<div class="container is-fullhd">
    <div class="notification is-primary">
        <h1><i class="fas fa-globe"></i>Sample SNS Application</h1> 
        <h3>~仕事の仲間と気軽に交流を楽しみましょう!!~</h3>
    </div>
</div>
{% endblock header %}

{% block content %}
{% if user.is_authenticated %}
<div class="container">
    <a href="{% url 'create' %}" class="button is-link is-large"><i class="fas fa-plus"></i>投稿する</a>
    {% for item in object_list %}
    <div class="card">
        <h5 class="card-header">投稿日 {{ item.created_at }}</h5>
        <h5 class="card-header">投稿者 {{ item.name }}</h5>
        <div class="card-body">
            <span class="tag is-{{ item.tag }} is-large">
                <h5 class="card-title">{{ item.title }}</h5>
            </span>
        </div>
    </div>
    {% endfor %}
    <a href="{% url 'logout' %}" class="button is-link">ログアウト</a>
</div>
{% else %}
please login.
<a href="{% url 'login' %}">ログイン</a>
{% endif %}
{% endblock content %}

ここはFont AwesomeやBootstrap, Bulmaで装飾して見た目を整えているような感じです。これで投稿した記事の一覧を表示できるようになります。


おわりに

今回の記事では、Djangoで投稿した記事の一覧を表示する機能を実装するための方法を詳細に解説しました。

次回の記事では、投稿した記事を実際に編集したり削除したりするCRUDモデルの作成を行っていきます。