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?

【初心者向け】Ruby on Railsで簡単なBBS(掲示板)を作成しよう!

Last updated at Posted at 2024-12-17

【初心者向け】Djangoで簡単なBBS(掲示板)を作成しよう!

概要

この記事では、PythonのWebフレームワークDjangoを使って、簡単なBBS(掲示板)を作成します。
最初に記事の一覧表示機能を作り、余力があれば新規登録・編集・削除機能を追加します。


前提条件

  • MAMP: ローカルサーバー環境を構築するツール。

  • Python: インストール済み(バージョン 3.10+ 推奨)。

  • Django: インストール済み(バージョン 4.x 推奨)。

  • VS Code: 開発用エディタ。


1. プロジェクトのセットアップ

1.1 仮想環境の作成

MAMPをインストールした状態で、プロジェクトディレクトリを作成します。

mkdir django_bbs
cd django_bbs
python -m venv venv
source venv/bin/activate   # Windowsでは venv\Scripts\activate

1.2 Djangoのインストール

仮想環境が有効になった状態で、Djangoをインストールします。

pip install django

1.3 プロジェクトの作成

Djangoプロジェクトを作成します。

django-admin startproject config .

1.4 アプリケーションの作成

掲示板用のアプリケーションを作成します。

python manage.py startapp bbs

作成後、config/settings.pyINSTALLED_APPS にアプリを追加します。

INSTALLED_APPS = [
    ...
    'bbs',
]

2. モデルの作成

2.1 Articleモデルの作成

bbs/models.py に以下を記述します。

from django.db import models

class Article(models.Model):
    content = models.TextField()

    def __str__(self):
        return self.content[:20]  # 短縮表示

2.2 マイグレーションの実行

データベースにモデルを反映させます。

python manage.py makemigrations
python manage.py migrate

3. 記事一覧表示の実装

3.1 ビューの作成

bbs/views.py を編集し、以下を記述します。

from django.shortcuts import render
from .models import Article

def article_list(request):
    articles = Article.objects.all()
    return render(request, 'bbs/article_list.html', {'articles': articles})

3.2 URL設定

bbs/urls.py を作成し、以下を記述します。

from django.urls import path
from .views import article_list

urlpatterns = [
    path('', article_list, name='article_list'),
]

次に、config/urls.py に以下を追加します。

from django.urls import path, include

urlpatterns = [
    path('', include('bbs.urls')),
]

3.3 テンプレートの作成

bbs/templates/bbs/article_list.html を作成し、以下を記述します。

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>BBS</title>
</head>
<body>
    <h1>掲示板</h1>
    <table border="1">
        <tr>
            <th>ID</th>
            <th>Content</th>
        </tr>
        {% for article in articles %}
        <tr>
            <td>{{ article.id }}</td>
            <td>{{ article.content }}</td>
        </tr>
        {% endfor %}
    </table>
</body>
</html>

3.4 動作確認

サーバーを起動し、ブラウザで確認します。

python manage.py runserver

http://127.0.0.1:8000 にアクセスすると、記事一覧が表示されます。
データがない場合は、Django管理画面またはシェルを使用してデータを追加します。


4. 新規登録・編集・削除機能の追加

4.1 フォームの作成

bbs/forms.py を作成し、以下を記述します。

from django import forms
from .models import Article

class ArticleForm(forms.ModelForm):
    class Meta:
        model = Article
        fields = ['content']

4.2 ビューの更新

bbs/views.py に以下を追加します。

from django.shortcuts import redirect, get_object_or_404
from .forms import ArticleForm

def article_new(request):
    if request.method == "POST":
        form = ArticleForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('article_list')
    else:
        form = ArticleForm()
    return render(request, 'bbs/article_form.html', {'form': form})

def article_edit(request, pk):
    article = get_object_or_404(Article, pk=pk)
    if request.method == "POST":
        form = ArticleForm(request.POST, instance=article)
        if form.is_valid():
            form.save()
            return redirect('article_list')
    else:
        form = ArticleForm(instance=article)
    return render(request, 'bbs/article_form.html', {'form': form})

def article_delete(request, pk):
    article = get_object_or_404(Article, pk=pk)
    article.delete()
    return redirect('article_list')

4.3 URLの追加

bbs/urls.py に以下を追加します。

from .views import article_new, article_edit, article_delete

urlpatterns = [
    path('', article_list, name='article_list'),
    path('new/', article_new, name='article_new'),
    path('<int:pk>/edit/', article_edit, name='article_edit'),
    path('<int:pk>/delete/', article_delete, name='article_delete'),
]

4.4 テンプレートの追加

4.4.1 フォームテンプレート

bbs/templates/bbs/article_form.html を作成します。

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>記事の作成</title>
</head>
<body>
    <h1>記事の作成/編集</h1>
    <form method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">保存</button>
    </form>
    <a href="{% url 'article_list' %}">戻る</a>
</body>
</html>

4.4.2 リストにリンクを追加

bbs/templates/bbs/article_list.html を編集します。

<a href="{% url 'article_new' %}">新規投稿</a>
<table border="1">
    <tr>
        <th>ID</th>
        <th>Content</th>
        <th>操作</th>
    </tr>
    {% for article in articles %}
    <tr>
        <td>{{ article.id }}</td>
        <td>{{ article.content }}</td>
        <td>
            <a href="{% url 'article_edit' article.id %}">編集</a> |
            <a href="{% url 'article_delete' article.id %}">削除</a>
        </td>
    </tr>
    {% endfor %}
</table>

5. 動作確認

  1. 新規投稿: フォームから記事を登録。
  2. 編集: 一覧画面のリンクを使用。
  3. 削除: 削除リンクをクリック。

これで、Djangoを使った簡単な掲示板が完成しました!次のステップでは、認証機能やデザインを加えてみてください。

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?