0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Djangoドキュメント作成3

Last updated at Posted at 2025-01-04

今回は前回の記事の続きから説明します

前回の記事はこちら↓
https://qiita.com/rinto____/items/36b1053a6728dd72b9ee

検索フォーム

新規ファイル作成

bbsフォルダ直下にforms.pyファイルを作成

bbs/forms.pyの編集

bbs > forms.py
# formで使える便利な機能をインポート
from django import forms

# 検索する用のクラスを作成
class SearchForm(forms.Form):
    keyword = forms.CharField(label='検索', max_length=100)   #全て追加する

bbs/views.pyの編集

bbs > views.py
from .forms import SearchForm

#省略

def index(request):   #indexの中身を書き換える
    searchForm = SearchForm(request.GET) 
    if searchForm.is_valid():
        keyword = searchForm.cleaned_data['keyword']
        articles = Article.objects.filter(content__contains=keyword).order_by('-id')
    else:
        searchForm = SearchForm()
        articles = Article.objects.all().order_by('-id')

    context = {'message': "Welcome my BBS",
                'articles': articles,
                'searchForm': searchForm,   #この1行を追加する
                }
    return render(request, 'bbs/index.html', context)

index.htmlで表示

index.htmlの編集

index.html
{% block content %}
<h1>Hello Django</h1>
<p>{{ message }}</p>
{% if searchForm %}   <!-- if文を追加する -->
<form action="{% url 'bbs:index' %}" method="get">
  <div class="form-group">
    {{ searchForm }}
    <input type="submit" class="btn btn-outline-primary" value="OK">
    <a href="{% url 'bbs:index' %}" class="btn btn-outline-secondary">クリア</a>
  </div>
</form>
{% endif %}
<p>
  <a href='{% url "bbs:create" %}' class="btn btn-primary">新規作成</a>
</p>

edit,update,new関数作成

ルーティング

bbs/urls.pyの編集

bbs > urls.py
urlpatterns = [
  path('', views.index, name='index'),
  path('<int:id>', views.detail, name='detail'),
  path('new', views.new, name='new'),   #この1行を追加する
  path('create', views.create, name='create'),
  path('<int:id>/edit', views.edit, name='edit'),   #この1行を追加する
  path('<int:id>/update', views.update, name = 'update'),   #この1行を追加する
  path('<int:id>/delete', views.delete, name='delete'),
]

ビュー

動作確認のために直接テキストを返す

bbs/views.pyの編集

bbs > views.py
#下記の関数全てを追加する
def new(request):
    return HttpResponse('new')

def edit(request, id):
    return HttpResponse(str(id)+'をedit')

def update(request, id):
    return HttpResponse(str(id)+'をupdate')

確認

下記のURLで画面が表示されるならOK

http://localhost:8000/bbs/new
http://localhost:8000/bbs/1/edit
http://localhost:8000/bbs/1/update

スクリーンショット 2024-12-30 19.55.00.png

スクリーンショット 2024-12-30 19.55.48.png

スクリーンショット 2024-12-30 19.56.33.png

フォームの作成

ライブラリインストール

フォームでBootstrapを使えるようにする

ターミナルで

pip install django-bootstrap4

エラーがでた場合pipではなくpip3を試してください

django-bootstrap4をDjangoで使うための設定

myapp/settings.pyの編集

myapp > settings.py
INSTALLED_APPS = [
    'bbs.apps.BbsConfig',
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "bootstrap4",   #この1行を追加
]

新規投稿フォーム

フォームの定義

bbs/forms.pyの編集

bbs > forms.py
from django import forms
from .models import Article  #この1行を追加する

#省略
#この下を追加する
class ArticleForm(forms.ModelForm):
    class Meta:
        model = Article
        fields = ('content', 'user_name')

データを保存、編集したい場合はModelFormを使用
Meta はDjangoフォームの特別なクラスで、フォームの情報を定義するために使用。フォームのバリデーションやデータベースへのデータ保存などが簡単にできる

ビュー

bbs/views.pyの編集

bbs > views.py
from django.shortcuts import render,get_object_or_404
from django.http import HttpResponse
from .models import Article
from .forms import SearchForm
from .forms import ArticleForm   #この1行を追加する

#省略

def new(request):   #new関数を編集する
    articleForm = ArticleForm()

    context = {
        'message': 'new Article',
        'articleForm':ArticleForm,
    }
    return render(request, 'bbs/new.html', context)

テンプレート

テンプレートファイル新規作成

bbs/templates/bbs/new.htmlを新規作成

bbs > templates > bbs > new.html
{% extends './base.html' %}   #全て追加する
{% load bootstrap4 %}

{% block content %}
<h1>{{ message }}</h1>

<form action="{% url 'bbs:create' %}" method="post" class="form">
  {% csrf_token %}
  {% bootstrap_form articleForm layout="horizontal" %}
  <button type="submit" class="btn btn-outline-primary">作成する</button>
<a href="{% url 'bbs:index' %}" class="btn btn-outline-secondary">戻る</a>
</form>
{% endblock %}

入力内容を確認

bbs/views.pyの編集

bbs > views.py
def create(request):
    if request.method == 'POST':   #ここからcontext前まで追加する
        articleForm = ArticleForm(request.POST)
        if articleForm.is_valid():
            article = articleForm.save()
            articles = Article.objects.all().order_by('-id')
    context = {'message': str(article.id)+"をArticleに追加",
                'article': article,
                }   #contextの中を書き換える
    return render(request, 'bbs/detail.html', context)   #bbs/indexからbbs/detailに変える

編集用フォーム

bbs/views.pyの編集

bbs > views.py
def edit(request, id):   #edit関数の中を編集
    article = get_object_or_404(Article, pk=id)
    # instance=article:フォームが既存の記事の情報を編集する際に使用
    articleForm = ArticleForm(instance=article)

    context = {
        'message': 'ページID:'+ str(id) +"を編集",
        'article': article,
        'articleForm': articleForm,
    }
    return render(request, 'bbs/edit.html', context)

テンプレート

templatesにedit.htmlファイル作成

bbs > templates > bbs > edit.html
{% extends './base.html' %}
{% load bootstrap4 %}

{% block content %}
<h1>{{ message }}</h1>
<form action='{% url "bbs:update" article.id %}' method="post" class="form">
  <!-- セキュリティーの為必須! -->
  {% csrf_token %}
  {% bootstrap_form articleForm layout="horizontal" %}
  <button type="submit" class="btn btn-outline-primary">保存</button>
<a href="{% url 'bbs:detail' article.id %}" class="btn btn-outline-secondary">戻る</a>
</form>
{% endblock %}

ビュー

bbs/views.pyの編集

bbs > views.py
def update(request, id):   #update関数の中を編集する
    if request.method == 'POST':
        article = get_object_or_404(Article, pk=id)
        articleForm = ArticleForm(request.POST, instance=article)
        if articleForm.is_valid():
            article.save()

    context = {
        'message': 'ページID:'+ str(id) +"を更新",
        'article': article,
    }
    return render(request, 'bbs/detail.html', context)

確認

スクリーンショット 2024-12-30 21.39.00.png

このような画面になり、全てのボタン、検索機能が動作していればOKです
また、詳細ページに遷移した後「一覧に戻る」「編集」「削除」が正常に作用できていればOKです

これでDjangoを用いて簡単なサイトをつくることができました。
長い記事でしたがここまでお付き合いいただきありがとうございました!

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?